我想序列化一個沒有默認構造函數的派生類。我正在使用反序列化構造函數模式。我讀過你必須註冊派生類的類型,所以我在輸出檔案中這樣做(outputArchive.register_type<Point>();
)。但是,當試圖向輸入存檔註冊相同類型時,我得到一個編譯器錯誤,說Point
沒有默認構造函數(它沒有)。我們在這種情況下做什麼?註冊一個沒有默認構造函數的類型
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/base_object.hpp>
#include <fstream>
class AbstractPoint
{
public:
virtual ~AbstractPoint(){}
virtual void DoSomething() = 0;
template<class TArchive>
void serialize(TArchive& archive, const unsigned int version)
{
// do nothing
}
};
class Point : public AbstractPoint
{
public:
Point(const double data) : mData(data) {}
void DoSomething(){}
template<class TArchive>
Point(TArchive& archive)
{
archive >> *this;
}
template<class TArchive>
void serialize(TArchive& archive, const unsigned int version)
{
// Without this, we get unregistered void cast
archive & boost::serialization::base_object<AbstractPoint>(*this);
archive & mData;
}
double mData;
};
int main()
{
std::shared_ptr<AbstractPoint> point(new Point(7.4));
std::ofstream outputStream("test.txt");
boost::archive::text_oarchive outputArchive(outputStream);
outputArchive.register_type<Point>();
outputArchive << point;
outputStream.close();
std::ifstream inputStream("test.txt");
boost::archive::text_iarchive inputArchive(inputStream);
//inputArchive.register_type<Point>(); // Compiler error: no Point::Point()
std::shared_ptr<AbstractPoint> pointRead(new Point(inputArchive));
Point* castedPoint = dynamic_cast<Point*>(pointRead.get());
std::cout << "Data: " << castedPoint->mData << std::endl;
return 0;
}
僅供參考我在這裏與分裂這個問題,http://stackoverflow.com/questions/35753953/common-confusions-with-serializing-polymorphic-types –