I have implemented serialisation by making sure that classes in an inheritance hierarchy implement virtual read and write functions:
class base
{
...
virtual void read(std::istream&)=0;
virtual void write(std::ostream&) const=0;
virtual std::string is_a() const;
};
BEGIN_NAMESPACE_1(io)
SERIALISE(base)
END_NAMESPACE_1
where the macro "SERIALISE" implements an overload of a "serialise" and a "deserialise" function to allow easy i/o via the base class pointer:
#define SERIALISE(TYPE)\
void deserialise( boost::shared_ptr<TYPE>& dat, std::istream& ifs )\
{\
std::string type;\
read(type, ifs);\
\
dat = TYPE::make_##TYPE(type);\
dat->read(ifs);\
}\
\
void serialise( const boost::shared_ptr<TYPE>& dat, std::ofstream& ofs )\
{\
write(dat->is_a(), ofs);\
dat->write(ofs);\
}
However, if the base class contains pure virtual functions, I get a compiler error "cannot allocate object of abstract type "base" because the following functions are pure within "base"...", presumably because the compiler attempts to instantiate the abstract base class when the class name is passed to the macro invocation. Is there a way of salvaging this i/o design?