|
Boost : |
From: Chris Fairles (chris.fairles_at_[hidden])
Date: 2007-09-18 10:57:08
I wanted the ability to serialize to binary archives (over a socket)
and xml archives (file) without writing code for the two cases (nvp
w/xml and no-nvp with non-xml).
I whipped up a quick make_nvp wrapper that simply forwards on the
value if not serializing to a xml archive. Others might find this
useful, not sure if its good behavior to have right in the library. It
does require adding the Archive type as a tempalte param to the
make_nvp call.
template <typename Archive, typename T>
struct make_nvp_impl {
typedef T& result_type;
static T& do_make_nvp(const char *tag, T & value)
{ return value; }
};
template <typename Archive, typename T>
struct make_nvp_impl<boost::archive::basic_xml_iarchive<Archive>, T> {
typedef boost::serialization::nvp<T> result_type;
static boost::serialization::nvp<T> do_make_nvp(const char *tag, T & value)
{ return boost::serialization::make_nvp(tag,value); }
};
template <typename Archive, typename T>
struct make_nvp_impl<boost::archive::basic_xml_oarchive<Archive>, T> {
typedef boost::serialization::nvp<T> result_type;
static boost::serialization::nvp<T> do_make_nvp(const char *tag, T & value)
{ return boost::serialization::make_nvp(tag,value); }
};
template <typename Archive, typename T>
typename make_nvp_impl<Archive, T>::result_type
make_nvp(const char* tag, T& value)
{ return make_nvp_impl<Archive,T>::do_make_nvp(tag,value); }
So now:
struct point {
int x, y;
template<class Archive>
void serialize(Archive &ar, const unsigned int /*version*/) {
ar & make_nvp<Archive>("x",x);
ar & make_nvp<Archive>("y",y);
}
};
will serialize properly for xml archives and non-xml archives.
Chris
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk