gpt4 book ai didi

c++ - 可以使用boost序列化对boost::container::strings进行序列化吗?

转载 作者:行者123 更新时间:2023-12-03 07:21:02 25 4
gpt4 key购买 nike

我正在尝试序列化包含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序列化吗?如果是,我在做什么不正确或丢失?

最佳答案

是。令人惊讶的是,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

关于c++ - 可以使用boost序列化对boost::container::strings进行序列化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65105987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com