Possible Duplicate:
Boost Serialization using polymorphic archives
I am trying to serialize my classes using a base pointer to a derived class, but that only serializes the base class.
I just read http://www.boost.org/doc/libs/1_32_0/libs/serialization/doc/special.html#registration, but both the export macro and the register function didn't seem to change anything.
Consider the following, very basic, class hierarchy:
#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
class A
{
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned int version)
{
std::cout << "A!\n";
}
};
class B : public A
{
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & boost::serialization::base_object<A>(*this);
std::cout << "B!\n";
}
};
int main()
{
std::ofstream of("mybin.bin");
boost::archive::binary_oarchive oa(of);
A* b = new B();
oa << b;
delete b;
return 0;
}
Output will be:
A!
Clearly, the output I'm looking for is A! B!. Is there any way this can be achieved ?
EDIT: Ok, after looking at the related entry in the comments, here is what is going on.
There was 3 things to change:
- class A should have a virtual function so that it is considered polymorphic
- need to export derived classes. BOOST_CLASS_EXPORT(B)
- oa << b instead of oa << *b
It works with a standard binary_oarchive, as well as the polymorphic_binary_oarchive.
EDIT2: When I have let's say b.cpp(.h) and main.cpp, the BOOST_CLASS_EXPORT results in duplicate symbols:
duplicate symbol boost::archive::detail::extra_detail::init_guid::g