Reputation: 675
I'm using boost serialization (v 1.55 and I'm trying to implement serialization behavior for foo
that is dependent on archive type (xml or binary). At the same time, I need to use the polymorphic archive types. Here is a trivial example:
#include <sstream>
#include <boost/archive/polymorphic_binary_iarchive.hpp>
#include <boost/archive/polymorphic_binary_oarchive.hpp>
#include <boost/archive/polymorphic_xml_iarchive.hpp>
#include <boost/archive/polymorphic_xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
using namespace boost::archive;
typedef polymorphic_binary_iarchive BI;
typedef polymorphic_binary_oarchive BO;
typedef polymorphic_xml_iarchive XI;
typedef polymorphic_xml_oarchive XO;
/*
typedef binary_iarchive BI;
typedef binary_oarchive BO;
typedef xml_iarchive XI;
typedef xml_oarchive XO;
*/
struct foo
{
void save(BO & ar, unsigned int const & version) const {}
void load(BI & ar, unsigned int const & version) {}
void save(XO & ar, unsigned int const & version) const {}
void load(XI & ar, unsigned int const & version) {}
BOOST_SERIALIZATION_SPLIT_MEMBER();
};
int main()
{
std::stringstream ss;
XO ar(ss);
foo f;
ar << BOOST_SERIALIZATION_NVP(f);
}
The code compiles if I use the non-polymorphic archive types, but with the polymorphic types, I get the following error
error: no matching function for call to ‘foo::save(boost::archive::polymorphic_oarchive&, const unsigned int&) const
so it seems that the archive type changes in the ar <<
call. Does anyone know how to implement this?
Upvotes: 0
Views: 814
Reputation: 393694
The whole point of polymorphic archives is that you cannot know up front what archive implementation is gonna be used. In fact, it could be an archive type that doesn't yet exist, implemented in a dynamically loaded, 3rdparty library:
The main utility of polymorphic archives will be to permit the buiding of class DLLs that will include serialization code for all present and future archives with no redundant code. (docs)
As soon as you start doing special handling for specific archive types, you're at the very least swimming upstream, and possibly asking for trouble.
I suggest you rethink the perceived need to detect the archive implementation at runtime. Even if there were a way to get at the RTTI typeid
of the implementing type at runtime,
In short, if you have special handling, codify it. Just implement a saveXml
function or saveAs(SaveOptions format)
. You can use polymorphic archives to implement the one of the two, and take xml_oarchive&
by reference (so you accept derived implementations just fine).
$0.02
Upvotes: 1