我在序列化多态类型时遇到问题。实际上我只是在几个文件中将示例拆分为:http://uscilab.github.io/cereal/polymorphism.html。它编译得很好,但在运行时我得到一个异常告诉我,我无法序列化在代码中到达此行时未注册的多态类型: oarchive(ptr1,ptr2); 应该将ptr1和ptr2的内容序列化为流。
我附上文件,以便任何人都能看到正在发生的事情。
提前感谢您的时间! 最好, 罗杰。
////////////// IBaseClass.h
#ifndef _IBASECLASS_H_
#define _IBASECLASS_H_
// A pure virtual base class
class IBaseClass
{
public:
virtual void sayType() = 0;
};
#endif
////////////// DerivedClass.h
#ifndef DERIVEDCLASS_H_
#define DERIVEDCLASS_H_
#include "IBaseClass.h"
#include <cereal/types/polymorphic.hpp>
class DerivedClass : public IBaseClass {
void sayType();
int x;
template<class Archive>
void serialize( Archive & ar )
{ ar( x ); }
};
#include <cereal/archives/binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/json.hpp>
// Register DerivedClassOne
CEREAL_REGISTER_TYPE(DerivedClass);
#endif /* DERIVEDCLASS_H_ */
////////////// DerivedClass2.h
#ifndef DERIVEDCLASS2_H_
#define DERIVEDCLASS2_H_
#include "IBaseClass.h"
#include <cereal/types/polymorphic.hpp>
class DerivedClass2 : public IBaseClass {
void sayType();
float y;
template<class Archive>
void serialize( Archive & ar )
{ ar( y ); }
};
#include <cereal/archives/binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/json.hpp>
CEREAL_REGISTER_TYPE(DerivedClass2);
////////////// main.cpp
#include "DerivedClass.h"
#include "DerivedClass2.h"
#include <iostream>
#include <fstream>
#include <memory>
#include <cereal/archives/xml.hpp>
#include <cereal/types/polymorphic.hpp>
int main(int argc, char* argv[])
{
{
std::ofstream os( "polymorphism_test.xml" );
cereal::XMLOutputArchive oarchive( os );
// Create instances of the derived classes, but only keep base class pointers
std::shared_ptr<IBaseClass> ptr1 = std::make_shared<DerivedClass>();
std::shared_ptr<IBaseClass> ptr2 = std::make_shared<DerivedClass2>();
oarchive( ptr1, ptr2 );
}
{
std::ifstream is( "polymorphism_test.xml" );
cereal::XMLInputArchive iarchive( is );
// De-serialize the data as base class pointers, and watch as they are
// re-instantiated as derived classes
std::shared_ptr<IBaseClass> ptr1;
std::shared_ptr<IBaseClass> ptr2;
iarchive( ptr1, ptr2 );
// Ta-da! This should output:
ptr1->sayType(); // "DerivedClassOne"
ptr2->sayType(); // "EmbarrassingDerivedClass. Wait.. I mean DerivedClassTwo!"
}
return 0;
}
答案 0 :(得分:0)
https://uscilab.github.io/cereal/polymorphism.html
由于您没有对谷物:: base_class(this)进行任何序列化,因此没有从派生类到基类的路径。尝试添加:
CEREAL_REGISTER_POLYMORPHIC_RELATION(BaseClass,DerivedClassOne) CEREAL_REGISTER_POLYMORPHIC_RELATION(BaseClass,EmbarrassingDerivedClass)