Boost logo

Boost Users :

From: Sohail Somani (sohail_at_[hidden])
Date: 2008-03-31 02:51:53


On Sun, 30 Mar 2008 14:41:16 -0700, Alex Idar wrote:

> I am looking for ideas about automatically generating the serialization
> helpers. Boost serialization library would be used - the question is
> about a simple (hopefully) and foolproof way of automatically creating
> the helpers.
>

I've always thought about this problem but have always decided that it
would be too inflexible. Anyway, here is one possible solution using the
Boost Preprocessor library:

#include <string>
#include <iostream>
#include <sstream>

#include <boost/preprocessor/tuple.hpp>
#include <boost/preprocessor/seq.hpp>

#include <boost/serialization/nvp.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

typedef boost::archive::text_oarchive test_oarchive_t;
typedef boost::archive::text_iarchive test_iarchive_t;

using namespace std;

#define DEF_MEMBER(r, data, elem) \
  BOOST_PP_SEQ_ELEM(0,elem) BOOST_PP_SEQ_ELEM(1,elem);

#define SERIALIZE_MEMBER(r, data, elem) \
  ar & BOOST_SERIALIZATION_NVP(BOOST_PP_SEQ_ELEM(1,elem));

#define SERIALIZABLE_MEMBERS(seq) \
  BOOST_PP_SEQ_FOR_EACH(DEF_MEMBER,~,seq) \
  template<typename Archive> \
  void serialize(Archive & ar, \
                 const unsigned int fv) \
  { \
    BOOST_PP_SEQ_FOR_EACH(SERIALIZE_MEMBER,~,seq); \
  }

struct person
{
  person(){}
  person(string name,
         string address):
    m_name(name),
    m_address(address)
  {}

  // Pass in a sequence of sequences.
  // Would really like to be able to say
  // SERIALIZABLE_MEMBERS((string, m_name) (string, m_address))
  // but couldn't get it to work for some reason.
  // Probably just my lack of understanding of the PP magic!
  SERIALIZABLE_MEMBERS(((string) (m_name))
                       ((string) (m_address)))

  friend ostream& operator<<(ostream& os, person const &p)
  {
    cout << "Name: " << p.m_name << " Address: " << p.m_address;
  }
};

int main()
{
  person p("Sohail Somani",
           "Vancouver, BC");

  ostringstream os;
  {
    test_oarchive_t oa(os);
    oa << boost::serialization::make_nvp("person",p);
  }
  person p2;
  {
    istringstream is(os.str());
    test_iarchive_t ia(is);
    ia >> boost::serialization::make_nvp("person",p2);
  }
  cout << "Original person: " << p << endl
       << "Serialized : " << p2 << endl;
}

-- 
Sohail Somani
http://uint32t.blogspot.com

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