C++ 可以使用boost序列化来序列化boost::container::字符串吗?

C++ 可以使用boost序列化来序列化boost::container::字符串吗?,c++,boost,boost-serialization,C++,Boost,Boost Serialization,我试图序列化一个包含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/ser

我试图序列化一个包含
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;    
}
#包括
#包括
#包括
#包括
#包括
#包括
班车
{
公众:
car(){}
汽车(boost::container::string make):make(make){}
boost::container::string-make;
私人:
好友类boost::serialization::access;
模板
无效序列化(存档和ar,常量未签名整数版本)
{
ar&make;
}
};
int main()
{
汽车我的车(“福特”);
std::stringstream-ss;
boost::archive::text\u oarchive oa(ss);
oa>新车;
}
但上述文件未能编译,错误如下:

boost/serialization/access.hpp:116:11: error: 'class boost::container::basic_string<char>' has no member named 'serialize'
boost/serialization/access.hpp:116:11:错误:“class boost::container::basic_string”没有名为“serializate”的成员
同样的代码可以更改为使用
std::string
,并且可以很好地编译


是否可以序列化
boost::container::strings
,如果是,我做得不正确或丢失了什么?

是。令人惊讶的是,必要的支持并没有融入到Boost中。不过,如果您查看字符串序列化标头内部,您会发现它支持“primitive”,只需一行代码即可启用它:

BOOST_CLASS_IMPLEMENTATION(boost::container::string, boost::serialization::primitive_type)
现在它的工作原理与
std::string
相同:

#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