Hi Robert, thanks for the quick answer. I went for the second idea and
made my base class abstract using a pure virtual member function.
Unfortunately, now I'm catching an unknown exception when trying to
deserialize.
It seems to me that the serializing lib still doesn't know that it's
deserializing an object of type derived2.
Here is what I'm doing right know:
#include
#include
#include
#include
#include
class base
{
public:
virtual void foo() =0;
unsigned int type() { return _type; }
protected:
base() : _type( 0 ) {}
base( unsigned int type) : _type( type ) {}
private:
friend boost::serialization::access;
template< class ARCHIVE >
void serialize( ARCHIVE& ar, const unsigned int version )
{
ar & _type;
}
private:
unsigned int _type;
};
BOOST_IS_ABSTRACT( base )
class derived1 : public base
{
public:
derived1() : base( 1 ), _value( 2.1 ) {}
virtual void foo() {}
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 ) {}
virtual void foo() {}
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.
try
{
base* b;
archive & b;
if( b->type() == 1 )
{
derived1* d1 = static_cast( b );
}
else
{
derived2* d2 = static_cast( b );
}
}
catch( std::exception e )
{
std::cout << e.what() << std::endl;
}
}
return 0;
}