【问题标题】:Can boost::container::strings be serialized using boost serialization?可以使用 boost 序列化来序列化 boost::container::strings 吗?
【发布时间】:2021-03-14 06:55:42
【问题描述】:

我正在尝试序列化一个包含 boost::container::string 的类

#include <iostream>
#include <cstdlib>
#include <boost/container/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>

class car
{
public:
    car() {}
    car(boost::container::string make) : make(make) {}
    boost::container::string make;

private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & make;
    }
};

int main()
{
    car my_car("ford");

    std::stringstream ss;
    boost::archive::text_oarchive oa(ss);
    oa << my_car;
    
    car new_car;
    boost::archive::text_iarchive ia(ss);
    ia >> new_car;    
}

但以上编译失败,报以下错误:

boost/serialization/access.hpp:116:11: error: 'class boost::container::basic_string<char>' has no member named 'serialize'

可以将相同的代码更改为使用std::string,并且可以正常编译。

boost::container::strings 可以序列化吗?如果可以,我做错了什么或遗漏了什么?

【问题讨论】:

    标签: c++ boost boost-serialization


    【解决方案1】:

    是的。令人惊讶的是,必要的支持并未包含在 Boost 中。虽然如果您查看字符串序列化标头内部,您会发现它支持“原始”,并且只需一行即可启用它:

    BOOST_CLASS_IMPLEMENTATION(boost::container::string, boost::serialization::primitive_type)
    

    现在它和std::string一样工作:

    Live On Coliru

    #include <boost/archive/text_oarchive.hpp>
    #include <boost/archive/text_iarchive.hpp>
    #include <boost/container/string.hpp>
    #include <iostream>
    
    BOOST_CLASS_IMPLEMENTATION(boost::container::string, boost::serialization::primitive_type)
    
    struct car {
        template<class Ar> void serialize(Ar& ar, unsigned) { ar & make; }
        boost::container::string make;
    };
    
    int main() {
        std::stringstream ss;
        {
            boost::archive::text_oarchive oa(ss);
            car my_car{"ford"};
            oa << my_car;
        } // close archive
    
        std::cout << ss.str() << "\n";
        
        boost::archive::text_iarchive ia(ss);
        car new_car;
        ia >> new_car;    
    }
    

    打印

    22 serialization::archive 17 0 0 ford
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      相关资源
      最近更新 更多