使用共享指针和模板增强序列化

时间:2014-03-05 09:05:33

标签: c++ serialization boost boost-serialization

我是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文件中实现共享指针?

1 个答案:

答案 0 :(得分:0)

该标头包含对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