我想将具有属性的类序列化为泛型类上的指针列表
这是泛型类派生的父类:
class Base{
public :
friend class boost::serialization::access;
virtual ~Base(){}
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
}
virtual string Getid() = 0 ;
};
通用类:
template<typename T>
class GenericBase : public Base
{
public:
friend class boost::serialization::access;
GenericBase<T>(string id){}
~GenericBase(){}
string id;
vector<T> data
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & boost::serialization::base_object<Base>(*this);
ar & BOOST_SERIALIZATION_NVP( id);
ar & BOOST_SERIALIZATION_NVP( data);
}
string Getid() { return id; }
};
我要序列化的类
class Use
{
public:
friend class boost::serialization::access;
int Id;
map<string, Base*> BaseDatas;
Use();
~Use();
};
因此,在阅读了 boost 序列化文档(http://www.boost.org/doc/libs/1_43_0/libs/serialization/doc/serialization.html#derivedpointers)之后,我在序列化代码中尝试了这个:
main(){
Use u = Use();
std::ofstream ofs(filename, ios::binary);
// save data to archive
boost::archive::binary_oarchive oa(ofs);
oa.template register_type<GenericBase<Type1> >();
oa.template register_type<GenericBase<Type2> >();
oa.template register_type<GenericBase<Type3> >();
oa<<u;
}
我收到一条消息,
错误:“模板”(作为消歧器)只允许在模板中使用
,所以我换了
oa.template register_type >();
经过
oa.register_type();
它有效,我已经能够以文本和二进制格式保存(我检查了数据)
现在加载,我只使用了这些行:
main(){
Use u;
std::ifstream ifs(filename, ios::binary);
// load data
ia.register_type<GenericBase<Type1> >();
boost::archive::binary_iarchive ia(ifs);
ia>>u;
}
它给我一个错误:
错误:没有匹配函数调用 'GenericBase::GenericBase()'
有人告诉我,我必须像此示例http://www.boost.org/doc/libs/1_43_0/libs/serialization/doc/serialization.html#constructors中那样覆盖 2 种保存和加载方法
namespace boost { namespace serialization {
template<class Archive>
inline void save_construct_data(
Archive & ar, const my_class * t, const unsigned int file_version)
{
// save data required to construct instance
ar << t->m_attribute;
}
template<class Archive>
inline void load_construct_data(
Archive & ar, my_class * t, const unsigned int file_version)
{
// retrieve data from archive required to construct new instance
int attribute;
ar >> attribute;
// invoke inplace constructor to initialize instance of my_class
::new(t)my_class(attribute);
}
}} // namespace ...
但是我必须在哪里定义它们?在 Use 类的声明中?以及如何与会员打交道
map<string, Base*> BaseDatas;
?
感谢您的帮助 ;)