上下文
我使用 Boost 序列化库来保存和加载系统对象。
我围绕这个库定义了实践,所以我总是从基类序列化(每个可序列化的类都继承自 ISerializable
)。
因此,true_type(即最派生的类型)不同于 this_type(即 ISerializable
)并且 true_type 存储在文件中。
我的问题
如何仅从存档对象中检索此 true_type(如存档中写入的字符串)?
详情
让我们有这个类树:
ISerializable <|-- B <|-- D
如果我这样做:
B* b = new D();
b->SaveToFile(path); // <= this will do the serialization `ar & this`
(`this` being a `ISerializable*`)
我获得了一个存档,其中写入了 true_type“D”(无论存档的类型是什么:txt、bin 或 xml)。
使用 b
对象和这段代码:
const boost::serialization::extended_type_info & true_type
= * boost::serialization::type_info_implementation<ISerializable>::type
::get_const_instance().get_derived_extended_type_info(*b);
我在 true_type.get_key()
中有我想要的东西,即:“D”。我可以验证每个存储 b
的存档中都写了“D”。我的问题又来了:如何才能仅使用存档对象(从存档文件无误地构建)检索此 key ?
最佳答案
应该是这样的:
B * b;
ar >> b;//loading archive
const boost::serialization::extended_type_info & true_type
= * boost::serialization::type_info_implementation<ISerializable>::type
::get_const_instance().get_derived_extended_type_info(*b);
因为保存的类型是D,所以loadad的类型也是D。
关于c++ - 如何从存档中检索 true_type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13130236/