1

I'm new to C++ and how do i serialize the struct having shared pointer and template . Below is sample code.

#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;
    }
}
}

now how do i implement in the corresponding Mydata.cpp file for shared pointer ?

sia
  • 1,872
  • 1
  • 23
  • 54

1 Answers1

0

That header includes support for boost::shared_ptr, so the following works:

#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;
}

See it Live On Coliru

sehe
  • 374,641
  • 47
  • 450
  • 633
  • above code do i need to implement it in Mydata.cpp file – sia Mar 06 '14 at 03:34
  • [Template definitions always go into headers](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file/495056#495056). Otherwise, it's your choice. If you don't want the serialization logic right there, you can look at [non-intrusive serialization adaption](http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#nonintrusiveversion) which doesn't require you to add members to existing (public or third party) classes – sehe Mar 06 '14 at 07:23