Ant*_*kov 12 c++ serialization boost
我想序列化/反序列化以下类:
class Feature{
...
virtual string str()=0;
};
template<typename T>
class GenericFeature : public Feature{
T value;
...
virtual string str();
};
Run Code Online (Sandbox Code Playgroud)
我读了boost.serialize docs,并说你必须注册类.我可以在构造函数中注册它们.但是加载会有问题,因为注册是动态的,而不是静态的(据我所知,你必须在序列化/反序列化之前注册类).
如何保存/加载这些类?
Arp*_*ius 15
首先告诉提示功能是抽象的,并不总是需要:
BOOST_SERIALIZATION_ASSUME_ABSTRACT(Feature);
Run Code Online (Sandbox Code Playgroud)
序列化方法应该看起来或多或少像这样:
template<class Archive>
void Feature::serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(some_member);
}
template<typename T,class Archive>
void GenericFeature<T>::serialize(Archive & ar, const unsigned int version)
{
ar & boost::serialization::base_object<Feature>(*this); //serialize base class
ar & BOOST_SERIALIZATION_NVP(some_other_member);
}
Run Code Online (Sandbox Code Playgroud)
现在最棘手的一点是在序列化/反序列化中注册类:
boost::archive::text_iarchive inputArchive(somesstream);
boost::archive::text_oarchive outputArchive(somesstream);
//something to serialize
Feature* one = new GenericFeature<SomeType1>();
Feature* two = new GenericFeature<SomeType2>();
Feature* three = new GenericFeature<SomeType3>();
//register our class, must be all of posible template specyfication
outputArchive.template register_type< GenericFeature<SomeType1> >();
outputArchive.template register_type< GenericFeature<SomeType2> >();
outputArchive.template register_type< GenericFeature<SomeType3> >();
// now simply serialize ;-]
outputArchive << one << two << three;
// register class in deserialization
// must be the same template specification as in serialize
// and in the same correct order or i'm get it wrong ;-D
inputArchive.template register_type< GenericFeature<SomeType1> >();
inputArchive.template register_type< GenericFeature<SomeType2> >();
inputArchive.template register_type< GenericFeature<SomeType3> >();
Feature* another_one;
Feature* another_two;
Feature* another_three;
// and deserialize ;-]
inputArchive >> another_one >> another_two >> another_three;
Run Code Online (Sandbox Code Playgroud)
如果你需要在某个地方隐藏显式注册并使其更加自动化,那么有想法制作一个特殊的仿函数模板来注册一个派生类,创建所有可用的并放入一个列表,类Feature的一个静态方法会将它们全部注册.但问题是你需要注册所有版本的存档,现在我不知道多态存档是否能完成这项工作.
归档时间: |
|
查看次数: |
8631 次 |
最近记录: |