我想序列一類具有作爲指針的列表上的通用類的屬性c + +升壓系列化序列化模板派生類
這是從哪個通用類派生的父類:
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();
};
所以,在閱讀升壓序列化文檔(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;
}
我得到一個消息,
error: 'template' (as a disambiguator) is only allowed within templates
,所以我換成了
oa.template register_type >();
通過
oa.register_type();
它的工作,我已經能夠在文本和二進制保存(我檢查了DATAS)
裝載現在,我只是用這些行:
main(){
Use u;
std::ifstream ifs(filename, ios::binary);
// load data
ia.register_type<GenericBase<Type1> >();
boost::archive::binary_iarchive ia(ifs);
ia>>u;
}
丟給我一個錯誤:
error: no matching function for call to 'GenericBase::GenericBase()'
有人告訴我,我不得不重寫2種方法保存和載入這樣的樣本http://www.boost.org/doc/libs/1_43_0/libs/serialization/doc/serialization.html#constructors
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 ...
在哪裏,但我必須去界定?在使用類的聲明中?我該如何處理會員
map<string, Base*> BaseDatas;
?
感謝您的幫助;)
不應該'類Use'從'Base'或'GenericBase'衍生? – Inverse 2010-08-02 12:16:20
不,使用類使用基地作爲一個屬性 – user408535 2010-08-02 14:23:01
您所提供的使用類缺少序列化功能。 – 2010-09-06 10:50:00