使用 Boost 对具有 const 成员的类进行序列化

serialization of class with const members using Boost

本文关键字:序列化 成员 const Boost 使用      更新时间:2023-10-16

请考虑以下代码片段

class tmp1
{
const int a_;
const double b_;   
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int ver)
{
ar & a_ & b_ ;
}
public:
tmp1(const itype a , const ftype b) : a_(a), b_(b)
{}
};

我可以将对象写入文件,通过

tmp1 t1(2, 10.0);    
std::string filename ="D:/Temp/demofile.txt";
std::ofstream ofs(filename);    
boost::archive::text_oarchive oa(ofs);
oa<<t1;

我想通过读取文件来构造另一个tmp1实例。理想情况下,我希望这发生在第二个构造函数中,该构造函数采用文件名并构造它。我该如何做到这一点?

我试过了

tmp1 t2(10, 100.0);
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
ia>>t2;

但 VS2012 编译失败,并显示以下消息

archive/detail/check.hpp(162): error C2338: typex::value
4>          boostboost_1_67_0boost/archive/detail/iserializer.hpp(611) : see reference to function template instantiation 'void boost::archive::detail::check_const_loading<T>(void)' being compiled
4>          with
4>          [
4>              T=const itype
4>          ]

我假设这是由于成员const.我以为 boost 会抛弃 const 限定符,但事实似乎并非如此。

您要查找的是文档中的"非默认构造函数":

https://www.boost.org/doc/libs/1_67_0/libs/serialization/doc/index.html

您需要为 编写重载

template<class Archive, class T>
void load_construct_data(
Archive & ar, T * t, const unsigned int file_version
);

因此,对于类 Foo,例如由整数和字符串构造的类,您将提供:

template<class Archive>
void load_construct_data(
Archive & ar, Foo * t, const unsigned int file_version
)
{
int a;
std::string b;
ar >> a >> b;
new (t) Foo(a, std::move(b));
}