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
#include
#include
#include
#include
#include
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