Boost logo

Boost Users :

From: Piyush Kapadia (piyush.kapadia_at_[hidden])
Date: 2005-11-01 09:15:27


We have a situation where there is BaseAbstract class and Derived concrete
class.
Interface requires that we pass BaseAbstractClassPointer, using which user
can provide any of Derived Concrete class pointer and Interface remain
generic to them.
 However serializing BaseAbstractPointer is throwing following error -
 *A unregistered class*
 How do we handle this situation ?

#include <iostream>
#include <fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/map.hpp>
#include <vector>
#include <map>
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/basic_xml_archive.hpp>

class BaseAbstract
{
public :
virtual void setRate(double rate) = 0;
virtual double getRate(int) = 0;
};

class DerivedConcrete : public BaseAbstract
{
std::vector<double> rateVec;

friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(rateVec);
}

public:
DerivedConcrete(double rate) {rateVec.push_back(rate);}

DerivedConcrete(){}
virtual ~DerivedConcrete(){}
void setRate(double rate){ rateVec.push_back(rate); };
double getRate(int idx){ return rateVec[idx]; };
};

class AnyClass
{
friend class boost::serialization::access;
BaseAbstract* rate;

template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(rate);
}
public:
AnyClass(BaseAbstract* rateInput){ rate = rateInput; };
AnyClass() {};
setRate(BaseAbstract* rateInput){ rate = rateInput; };
};

int main(int argc, char* argv[])
{
try {
DerivedConcrete* fr = new DerivedConcrete(12.12);
fr->setRate(14.5);
AnyClass ac;
ac.setRate(fr);
std::ofstream ofs("AC.xml");
assert(ofs.good());
boost::archive::xml_oarchive oa(ofs);
oa << BOOST_SERIALIZATION_NVP(ac);
ofs.close();

}
catch (boost::archive::xml_archive_exception ex)
{
std::cerr << " X " << ex.what() << std::endl;
}
catch (boost::archive::archive_exception ex)
{
std::cerr << " A " << ex.what() << std::endl;
}
catch (std::exception ex)
{
std::cerr << " E " << ex.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown Exception " << std::endl;
}
return 0;
}



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net