|
SerializationSerialization Wrappers |
BOOST_STRONG_TYPEDEF
boost::serialization::binary_object(void * t, size_t size);
boost::serialization::make_binary_object(void * t, size_t size);
which will construct a temporary binary object that can be serialized just like any other object.
Its default serialization is to use archive class primitives
save_binary
and load_binary
.
Note that it doesn't allocated any storage or create any objects.
Its sole purpose is to pass the data size and address as pair to the archive class.
BOOST_STRONG_TYPEDEF
BOOST_STRONG_TYPEDEF
template.
The serialization libraries uses these to pass particular kinds of integers such
as object_id, version, etc. to an archive class. Given that these integers
are now distinguishable according to their type, XML archives can apply
special handling to these types. For example, a version number is rendered
as an XML attribute in the form "version=12". In the absence of any specific override,
these types are automatically converted to the underlying integer type so the
special overrides used for XML archives aren't needed for other archives.
Our solution is to wrap class members to be serialized in a
name-value-pair. This structure is defined in
nvp.hpp.
It is just a reference to the data member coupled with a pointer to
to a const char *
which corresponds to the XML name.
The xml archive classes contain code similar to:
// special treatment for name-value pairs.
template<class T>
xml_oarchive & operator&(const boost::serialization::nvp & t)
{
// write an xml start tag
start_tag(t.name());
// serialize the data as usual
*this & t.value();
// write an xml end tag
end_tag(t.name());
}
Archive classes which don't use the name of the data item include
code similar to the following:
// special treatment for name-value pairs. In a simple
// text archive, just output the value in the normal way.
// the name is not used
template<class IStream, class T>
text_oarchive & operator&(const boost::serialization::nvp & t)
{
*this & t.value();
}
That is, the name part is ignored and and the value part is serialized
as usual.
Hence, adding the name of the data item does not in any way affect the usage of archives which don't use it.
The most obvious and convient name to assign to as the XML data item name is - surpise! - the name of the C++ class data member. So our serialization code will look like:
ar & make_nvp("my_variable", my_variable);
To simplify typing and enhance readability a macro is defined so we can write:
ar & BOOST_SERIALIZATION_NVP(my_variable);
Similarly there exists a macro definition that permits us to write:
BOOST_SERIALIZATION_BASE_OBJECT_NVP(my_base_class)
Included is demo_xml.hpp which renders it's data members as name-value-pairs and demo_xml.cpp which saves and loads data to an XML archive. Here is example of the XML Archive corresponding to our tutorial example.
ar & make_nvp("named_binary_object", make_binary_object(address, size));