使用 Boost 对具有 const 成员的类进行序列化
serialization of class with const members using Boost
请考虑以下代码片段
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));
}
相关文章:
- 如何在C++中序列化结构数据
- 为什么在C++中首先初始化成员类
- 提升 - 类没有名为"序列化"的成员(抽象类)?
- 使用 Boost::Serialization 序列化具有 std::mt19937_64 成员的类
- 使用 Boost 对具有 const 成员的类进行序列化
- 使用<string>提升::序列化序列化具有 vector<unique_ptr> 成员的类
- C++ Boost.Serialization - 用户定义成员的非侵入式序列化
- 使用构造函数作为成员函数的 C++(用于序列化)
- 序列化具有不同成员 MFC c++ 的继承类
- 如何将序列化方法添加到作为Windows数据结构的类成员中,以便在C++中与boost序列化一起使用
- 在使用 boost::序列化时,是否应该序列化没有成员变量的基本对象
- 端口项目 VS2003 -> VS2013 错误 C2039 序列化不是hash_Map的成员
- C/C++:序列化方法应该是类成员吗
- 跟踪何时为增强序列化添加数据成员
- 增强引用成员抽象类的序列化
- Boost序列化:在反序列化时更新成员
- 具有boost::shared_ptr类型成员的std::map的序列化失败
- 增强类序列化,更改成员类型
- 使用自定义类的Qlist作为成员序列化类(使用QDataStream)
- 获取用于非侵入性提升序列化C++的私有数据成员