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

标签 c++ serialization boost constructor constants

考虑以下代码片段

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>          \boost\boost_1_67_0\boost/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++ - 使用 Boost 对具有 const 成员的类进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50603180/

相关文章:

boost - 使用 boost::chrono 而不链接到它

c++ - 关于 C++ 中的 & 运算符的问题

c++ - 数独求解算法C++

java - Parcelable 与 Serialized - 对于没有任何字段的类

java - java和c#中的序列化集成解决方案?

c++ - 如何从 boost::multi_index_container 中检索元素

c++ - 使用 cin 在一行上读取多个 int

c++ - C++中的指针和删除

c++ - 保存和加载 C++ 程序

c++ - Boost:阻塞直到队列有另一个项目