Christophe
Christophe

Reputation: 305

Could I use boost::serialization library to serialize a union-like class of C++

I have implemented an union-like class which is learnt from C++ Primer section 19.6.

Is there any chance to serialize it by using boost::serialization library?

Upvotes: 0

Views: 380

Answers (1)

sehe
sehe

Reputation: 392931

Sure:

Live On Coliru

#include <iostream>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/variant.hpp>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>

using V = boost::variant<std::string, double, int>;

int main()
{
    boost::archive::text_oarchive oa(std::cout);
    oa << std::vector<V> { 3.14, "std::string", 42 };
}

Prints

22 serialization::archive 14 0 0 3 0 0 0 1 3.14000000000000012e+00 0 11 std::string 2 42

Use a binary_archive or xml_archive. Suppress headers if you must. You can of course deserialize and add variant members with custom serialization.

Upvotes: 1

Related Questions