simple serialization of boost::variant

I use std::istream and std::ostream for binary serialization ( can't use
boost::serialization) and can't find a way to serialize boost::variant

Archie14
I use std::istream and std::ostream for binary serialization ( can't use boost::serialization) and can't find a way to serialize boost::variant
. I'll appreciate a code sample or link to the documentation. Thanks.
This is a hack I came up with: for ostream - using visitor pattern: class outptype : public boost::static_visitor<> { public: outptype(std::ostream& stream) : _stream(stream){} void operator()(const int & i) { _oftype = 1; writevalue<byte>(_stream, _oftype); writevalue<int32>(_stream, i); } void operator()(const std::string & str) { _oftype = 2; writevalue<byte>(_stream, _oftype); writevaluestd::string(_stream, str); } void operator()(const double & val) { _oftype = 3; writevalue<byte>(_stream, _oftype); writevalue<double>(_stream, val); } private: std::ostream& _stream; byte _oftype; }; and for istream: byte oftype = readvalue<byte>(stream); switch (oftype) { case 1: { int temp = readvalue<int32>(stream); break; } case 2: { std::string temp = readvaluestd::string(stream); break; } case 3: { double temp = readvalue<double>(stream); break; } default: break; } return stream; } Is that directionally correct?

Zitat von Archie14
I use std::istream and std::ostream for binary serialization ( can't use boost::serialization) and can't find a way to serialize boost::variant
. I'll appreciate a code sample or link to the documentation. Thanks.
boost/serialization/variant.hpp you could either use that code, even though you're not using a archive from Boost.Serialization, but it also shows how to serialize a boost::variant if you want to write your own code (visitor for saving, iteration for loading)
participants (2)
-
Archie14
-
Stefan Strasser