Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish read / write operation in boost serialization?

Using the boost serialization library I have a very simple serialize() member function, something like:

template <class Archive>
  void serialize( Archive& ar, unsigned version )
  {
     ar & m_Searcher;
  }

... and I want to keep it this simple (I don't want to use splitting in particular). But in the case of writing I want to do some "preparation" for m_Searcher before actual writing to take place.

{
  if( this-is-a-writing-operation )
     do-some-preparation( m_Searcher )

  ar & m_Searcher;
}

Is there any simple way to distinguish between reading and writing operations?

like image 463
Vladimir Ignatov Avatar asked Sep 08 '10 14:09

Vladimir Ignatov


1 Answers

I think you can do this without splitting, which would be the usual way:

if (Archive::is_saving::value) 
   doSomething();

This is inherited from the base interface that the Archives use, in boost/archive/detail/interface_[ia]archive.hpp

The following code demonstrates that it seems to be a reasonable solution with 1.42

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

// oarchive:
//text
static_assert(!boost::archive::text_oarchive::is_loading::value, "out is loading");
static_assert(boost::archive::text_oarchive::is_saving::value, "out isn't saving");

//xml
static_assert(!boost::archive::xml_oarchive::is_loading::value, "out is loading");
static_assert(boost::archive::xml_oarchive::is_saving::value, "out isn't saving");

// iarchive:
//text
static_assert(boost::archive::text_iarchive::is_loading::value, "out is loading");
static_assert(!boost::archive::text_iarchive::is_saving::value, "out isn't saving");

//xml
static_assert(boost::archive::xml_iarchive::is_loading::value, "out is loading");
static_assert(!boost::archive::xml_iarchive::is_saving::value, "out isn't saving");

I'd be a bit cautious of relying on something like this though -- multiple inheritance might break it if someone wrote an archive that does both input and output and it's not clear to me how permenant and public this part of the interface is meant to be.

like image 165
Flexo Avatar answered Nov 12 '22 08:11

Flexo