boost::container::strings 可以使用 boost 序列化进行序列化吗?

Can boost::container::strings be serialized using boost serialization?

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

的 class
#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 序列化吗?如果可以,我做错了什么或遗漏了什么?

是的。令人惊讶的是,必要的支持并没有融入 Boost。尽管如果您查看字符串序列化 header 内部,您会发现它具有作为“原始”的支持,并且只需要一行即可启用它:

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