C++ 谷物:在没有默认构造函数的情况下反序列化对象向量
我正在尝试使用来序列化没有默认构造函数的对象。直接或通过智能指针存储此类对象是可行的。然而, 当我将对象放入容器时,它不再编译:C++ 谷物:在没有默认构造函数的情况下反序列化对象向量,c++,cereal,C++,Cereal,我正在尝试使用来序列化没有默认构造函数的对象。直接或通过智能指针存储此类对象是可行的。然而, 当我将对象放入容器时,它不再编译: 错误:对“Node::Node()”的调用没有匹配的函数。 有没有一种方法可以在没有默认构造函数的情况下存储/恢复对象的向量 我的测试代码: #include <fstream> #include <cereal/archives/json.hpp> #include <cereal/types/memory.hpp> #inclu
错误:对“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;
}
#包括
#包括
#包括
#包括
类节点{
公众:
节点(int*父节点){};
int值_1;
模板
作废序列化(存档和存档){
档案馆(
谷物NVP(价值1)
);
}
模板
静态无效荷载和构造(归档和归档,谷物::构造和构造){
构造(nullptr);
构造->序列化(存档);
}
};
int main(){
std::string file_path=“../data/nodes.json”;
Node_1{nullptr};//这将序列化
std::vector nodes;//这不是
nodes.push_back(Node{nullptr});
nodes.push_back(Node{nullptr});
std::vector node_ptrs;//这将序列化
node_ptrs.push_back(std::make_unique(nullptr));
node_ptrs.push_back(std::make_unique(nullptr));
{//存储向量
std::流输出文件(文件路径);
谷物:JSONOutputArchive out\u archive(out\u文件);
out_归档(谷物NVP(节点));
}
{//负载向量
std::ifu文件中的流(文件路径);
谷物::JSONInputArchive in_归档(在_文件中);
in_归档(节点);
}
返回0;
}
就我所理解的这个库的工作方式而言,对于没有默认构造函数(至少对于动态分配的对象是这样)的东西,没有办法进行反序列化
其逻辑如下:
向量
想象一下加载一个没有默认构造函数的类型的场景。谷物序列化的接口要求您传递对要用序列化数据实例化的对象的引用。在没有默认构造函数的情况下,您(用户)必须已经初始化了这样一个对象,然后才能看到它。另一种方法是让谷物进行对象的实际构造,这只能在动态创建(即指针)对象时发生,以便谷物可以预加载要传递给构造函数的参数,如
load\u和\u construct
中所述。