2
我试图使用Cereal来序列化没有默认构造函数的对象。直接存储这些对象或通过智能指针工作。然而, 当我把物体放入容器,它不再编译:谷物:反序列化没有默认构造函数的对象向量
error: no matching function for call to ‘Node::Node()’
有没有办法让谷物存储/恢复对象的载体没有默认构造函数?
我的测试代码:
#include <fstream>
#include <cereal/archives/json.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/vector.hpp>
class Node {
public:
Node(int* parent) {};
int value_1;
template<class Archive>
void serialize(Archive& archive) {
archive(
CEREAL_NVP(value_1)
);
}
template<class Archive>
static void load_and_construct(Archive& archive, cereal::construct<Node>& construct) {
construct(nullptr);
construct->serialize(archive);
}
};
int main() {
std::string file_path = "../data/nodes.json";
Node node_1{nullptr}; // this would serialize
std::vector<Node> nodes; // this does not
nodes.push_back(Node{nullptr});
nodes.push_back(Node{nullptr});
std::vector<std::unique_ptr<Node>> node_ptrs; // this would serialize
node_ptrs.push_back(std::make_unique<Node>(nullptr));
node_ptrs.push_back(std::make_unique<Node>(nullptr));
{ //store vector
std::ofstream out_file(file_path);
cereal::JSONOutputArchive out_archive(out_file);
out_archive(CEREAL_NVP(nodes));
}
{ // load vector
std::ifstream in_file(file_path);
cereal::JSONInputArchive in_archive(in_file);
in_archive(nodes);
}
return 0;
}
想象一下加载没有默认构造函数的类型的场景。谷物序列化的接口要求你传递一个引用到要用序列化数据实例化的对象。在没有默认构造函数的情况下,您(用户)必须已经在谷物甚至看到它之前初始化了这样的对象。另一种方法是让谷物做对象的实际构造,这只能在动态创建(即指针)对象时才会发生,这样谷物就可以预先加载参数传递给构造函数,如'load_and_construct'中所示。 – Azoth