c++ boost::container::string可以用boost序列化吗?

4szc88ey  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(205)

我正在尝试序列化一个包含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可以被序列化吗?如果可以,我做错了什么?

js4nwp54

js4nwp541#

注意事项

事实证明(至少在今天)这个答案是不正确的。
是的。令人惊讶的是,必要的支持并没有被烘焙到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

相关问题