Hi there, I'm having problems when serializing derived classes from a
non-polymorphic base class. I have read the section "Pointers to
Objects of Derived Classes". But for some reasons I cannot make these
tricks to work in my application. I have created a small sample
application that shows my problem:
class base
{
public:
base() : _type( 0 ) {}
base( unsigned int type) : _type( type ) {}
unsigned int type() { return _type; }
private:
friend boost::serialization::access;
template< class ARCHIVE >
void serialize( ARCHIVE& ar, const unsigned int version )
{
ar & _type;
}
private:
unsigned int _type;
};
class derived1 : public base
{
public:
derived1() : base( 1 ), _value( 2.1 ) {}
private:
friend boost::serialization::access;
template< class ARCHIVE >
void serialize( ARCHIVE& ar, const unsigned int version )
{
ar & boost::serialization::base_object<base>( *this );
ar & _value;
}
private:
double _value;
};
class derived2 : public base
{
public:
derived2() : base( 2 ), _value( 8 ) {}
private:
friend boost::serialization::access;
template< class ARCHIVE >
void serialize( ARCHIVE& ar, const unsigned int version )
{
ar & boost::serialization::base_object<base>( *this );
ar & _value;
}
private:
short _value;
};
BOOST_CLASS_EXPORT( derived1 );
BOOST_CLASS_EXPORT( derived2 );
int _tmain(int argc, _TCHAR* argv[])
{
std::string data;
{
std::ostringstream archive_stream;
boost::archive::binary_oarchive archive( archive_stream );
derived2 d;
archive & d;
data = archive_stream.str();
}
{
// deserialize
std::string archive_data( &data[0], data.size() );
std::istringstream archive_stream( archive_data );
boost::archive::binary_iarchive archive( archive_stream );
// I don't know what derived class was serialized.
base* b;
archive & b;
if( b->type() == 1 )
{
derived1* d1 = static_cast