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

问题描述 投票:0回答:1

我正在尝试序列化一个包含

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个回答
1
投票

注意

事实证明(至少在今天)这个答案已经被打破了。看 使用自定义分配器对 std::basic_string 进行 Boost 序列化以获得适用于 Boost 1.83.0 的更好解决方案

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

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

现在它的工作原理与

std::string
相同:

住在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
© www.soinside.com 2019 - 2024. All rights reserved.