Boost logo

Boost Users :

Subject: Re: [Boost-users] simple serialization of boost::variant
From: Archie14 (admin_at_[hidden])
Date: 2010-05-27 21:46:40


Archie14 <admin <at> tradeplatform.us> writes:

>
> 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<int,
> double, std::string>. 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);
                writevalue<std::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 = readvalue<std::string>(stream);
                        break;
                }
        case 3:
                {
                        double temp = readvalue<double>(stream);
                        break;
                }
        default:
                break;
        }
        return stream;
}

Is that directionally correct?


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net