#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/string.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
struct Actioner
{
void ShowStrings(const std::string & a, const std::string & b)
{
using namespace std;
cout << "ShowStrings(" << a << ", " << b << ")" << endl;
}
void ShowDoubles(double a, double b, double c, double d)
{
using namespace std;
cout << "ShowDoubles(" <<
a << ", " <<
b << ", " <<
c << ", " <<
d << ")" << endl;
}
};
struct Base
{
virtual void Execute(Actioner & actioner) = 0;
template <class Ar>
void serialize(Ar & ar, const unsigned int ver)
{
}
};
struct Strings : Base
{
std::string a, b;
Strings()
{
}
Strings(const std::string & a, const std::string & b) : a(a), b(b)
{
}
void Execute(Actioner & actioner)
{
actioner.ShowStrings(a, b);
}
template <class Ar>
void serialize(Ar & ar, const unsigned int ver)
{
ar & boost::serialization::base_object<Base>(*this);
ar & a & b;
}
};
struct Doubles : Base
{
double a, b, c, d;
Doubles()
{
}
Doubles(double a, double b, double c, double d) : a(a), b(b), c(c), d(d)
{
}
void Execute(Actioner & actioner)
{
actioner.ShowDoubles(a, b, c, d);
}
template <class Ar>
void serialize(Ar & ar, const unsigned int ver)
{
ar & boost::serialization::base_object<Base>(*this);
ar & a & b & c & d;
}
};
struct Serializer
{
int numObjects;
Serializer() : numObjects(0)
{
}
template <class Ar>
void Serialize(Ar & ar, Base * subject)
{
ar << subject;
delete subject;
numObjects++;
}
};
BOOST_CLASS_EXPORT(Strings);
BOOST_CLASS_EXPORT(Doubles);
int main()
{
const char * kFilename = "s10n.dat";
int numObjects = 0;
{
std::ofstream stream(kFilename, std::ios::binary);
boost::archive::text_oarchive oa(stream);
Serializer ser;
ser.Serialize(oa, new Strings("Hello", "World"));
ser.Serialize(oa, new Strings("Foo", "dolor"));
ser.Serialize(oa, new Doubles(10, 20, 30, 40));
ser.Serialize(oa, new Strings("Baz", "ipsum"));
ser.Serialize(oa, new Doubles(100, 200, 300, 400));
ser.Serialize(oa, new Doubles(9, 3.1416, -3.1416, 99.99));
ser.Serialize(oa, new Strings("Gr", "Lorem"));
ser.Serialize(oa, new Doubles(1, 3, 5, 7));
numObjects = ser.numObjects;
using namespace std;
cout << "Serialized " << numObjects << " objects" << endl;
}
{
std::ifstream stream(kFilename, std::ios::binary);
boost::archive::text_iarchive ia(stream);
Actioner someone;
for(int i = 0; i < numObjects; ++i)
{
Base * thing;
ia >> thing;
thing->Execute(someone);
delete thing;
}
}
return 0;
}