Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-11-22 11:05:49

Richard Peters wrote:
> Hello,
> I'm looking for a way to serialize a variant. I see two possibly
> difficult things that I don't know how to accomplish: 1) In order to
> be able to retrieve a variant from an archive, the type of the value
> held by the
> variant must be stored. 2) When retrieving the data from an archive,
> once
> the type is read, a value of that type must be extracted from the
> archive
> and assigned to the variant. Has anybody tried this before, is this as
> difficult as it looks? Any help would be greatly appreciated.

I would expect the external representation of a variant<T1, ..., Tn> to be:

int index;
Ti ti;

where index denotes the type and is returned by varant<>::which().

Assuming a variant<int, string> for simplicity, the save pseudocode should
be something like:

int index = v.which();
ar << v;

switch( v )
case 0: ar << get<int>( v ); break;
case 1: ar << get<string>( v ); break;

You can rewrite it generically in terms of apply_visitor:

struct variant_saver
    typedef void result_type;

    template<class A, class T> void operator( A & a, T const & t ) const
        a << t;

apply_visitor( bind( variant_saver(), ref(ar), _1 ), v );

Disclaimer: I haven't compiled any of this. ;-)

Loading should be the reverse operation:

    int index;
    ar >> index;

    switch( index )
    case 0: { int t; ar << t; v = t; break; }
    case 1: { string t; ar << t; v = t; break; }

This, of course, belongs in variant.hpp. Don't let our shared_ptr debates
fool you. :-)

Boost list run by bdawes at, gregod at, cpdaniel at, john at