Question

I am using boost::variant and boost::serialize in my application. The serialization module has built in support for serializing variants, so:

boost::variant<int,double> u(3.14);

// Do something with u;

// Serialize
oa << u;

works. However, my problem is that the serialization is not robust. Depending on how my application is compiled the elements of the variant may change. Currently the serialization module appears to be simply embedding the index of the 'active' variant type; which is an issue if the variant changed to, say, boost::variant<double,string>.

Can anyone suggest ways of improving this so that the serialization/un-serialization works so as the type that has been serialized is a template parameter of the boost::variant. (So, in the above case boost::variant<int,double> u(3.14) could be un-serialized to a boost::variant<double,std::string>. I am aware this may require me to provide additional information such as a stringified form of the type.

Was it helpful?

Solution

How would an off-the-shelf mechanism for such a thing work? For instance, what should it do if you changed boost::variant<int,double> to boost::variant<int,std::string> and can no longer hold a double? Throw an exception?

If you want something like that I'd imagine you'd have to write it yourself to cover the cases you're anticipating and fit your definition of "robust".

You might also build in some file upgrading logic...for instance every version N of your program keeps around old copies of the definitions of structures for (N-1, N-2...) so that you're able to write routines that can be used in offering the ability to upgrade old files it encounters.

But really, it's best to get your file formats right the first time as much as possible, before you let the program out into the wild! Especially the data encoding the user's intent (derived structures that are effectively just caches can be thrown away and recomputed if a version doesn't recognize them).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top