gpt4 book ai didi

c++ - 使用共享指针和模板 boost 序列化

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:17 24 4
gpt4 key购买 nike

我是 C++ 的新手,我如何序列化具有共享指针和模板的结构。以下是示例代码。

#pragma once

#include <boost/serialization/access.hpp>
#include <boost\serialization\string.hpp>
#include <boost\serialization\shared_ptr.hpp>

//Mydata.hpp file

namespace mydata
{

struct MyData
{
std::string name;
std::string type;
std::shared_ptr<MyInfo> myref;

private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int vs)
{
ar & name;
ar & type;
ar & myref;
}
}
}

现在如何在相应的 Mydata.cpp 文件中实现共享指针?

最佳答案

该 header 包括对 boost::shared_ptr 的支持,因此以下工作:

#include <boost/serialization/access.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/smart_ptr/make_shared.hpp>

namespace mydata
{
struct MyInfo
{
std::string info = "extra info";

MyInfo(std::string info) : info(std::move(info)) {}

friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int /*version*/)
{
ar & info;
}
};

struct MyData
{
std::string name;
std::string type;
boost::shared_ptr<MyInfo> myref;

private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int /*version*/)
{
ar & name;
ar & type;
ar & myref;
}
};
}

int main()
{

using namespace mydata;
MyData data { "this is a name", "this is a type", boost::make_shared<MyInfo>("this is info") };

boost::archive::text_oarchive oa(std::cout);
oa << data;
}

查看 Live On Coliru

关于c++ - 使用共享指针和模板 boost 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22193052/

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