Serializing an object

#include <x/serialize.H>

int intvalue;

std::vector<std::string> strarray;

// ...

std::ofstream ofs("object.dat");

std::ostreambuf_iterator<char> ofs_iter(ofs.rdbuf());

x::serialize::iterator<std::ostreambuf_iterator<char> >
    o_iter(ofs_iter);

o_iter(intvalue);
o_iter(strarray);

The x::serialize namespace defines a iterator template class. The iterator output iterator implements an operator() that serializes its argument. The parameter to the template class is an output iterator class. std::ostreambuf_iterator<char> is the popular choice. The constructor takes a reference to the output iterator of this class. iterator saves a reference to the output iterator, which must exist as long as the iterator object itself remains in scope. The output iterator's value type must be either char or unsigned char.

iterator::operator() serializes the passed object into the output iterator. It returns a reference to this, allowing for the following shorthand:

o_iter(intvalue)(strarray);