Question

Below is example code wherein i'm trying to do serialization using boost. For struct my_type serialize method is implementated but how do i serialize my_time and data_type as bcoz they are in different namespace

// MyData.hpp

namespace X { namespace Y {

struct my_type
{

      std::string a;
      double b;

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

   public:
       my_type();
       my_type(const parameter_strings & parms);

       virtual ~my_type();

};


namespace Z
{
    typedef unsigned int my_time;
    typedef std::string data_type;
}


}
}

//MyData.cpp

#include <MyData.hpp>

my_type:: my_type()
{
}

my_type::~ my_type()
{
}

 my_type:: my_type(const parameter_strings & parms)
{   
    // implemetation
}

Since my_time and data_type are not inside any class or struct hence i don't how do serialize it. what way i should serialize my_time and data_type in MyData.cpp file and if there is an it will be really helpful.

Thanks

Was it helpful?

Solution

There's nothing you have to do.

my_time and data_type are aliases for the types they are declared with.

Boost serialization has built-in support for std::string and int and won't see the difference.

Relevant information:

See it Live On Coliru:

#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/serialization.hpp>

namespace X { namespace Y {

    struct my_type {
        std::string a;
        double b;

    private:
        friend class boost::serialization::access;
        template<class Archive>
        void serialize(Archive &ar, unsigned) {
            ar & a;
            ar & b;
        }

    public:
        my_type(){}
        virtual ~my_type(){}
    };


    namespace Z
    {
        typedef unsigned int my_time;
        typedef std::string data_type;
    }

} }

#include <iostream>

int main()
{
    boost::archive::text_oarchive oa(std::cout);
    X::Y::my_type a;
    a.a = "in my_type";
    a.b = 3.14;
    X::Y::Z::my_time b = 42;
    X::Y::Z::data_type c = "hello world";

    oa << a << b << c;
}

Prints

22 serialization::archive 10 0 0 10 in my_type 3.1400000000000001 42 11 hello world
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top