gpt4 book ai didi

c++ - Cereal:序列化多态类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:16 25 4
gpt4 key购买 nike

我在序列化多态类型时遇到问题。实际上,我只是将示例拆分为:http://uscilab.github.io/cereal/polymorphism.html在几个文件中。它编译得很好但在运行时我得到一个异常告诉我我无法序列化到达代码中这一行时未注册的多态类型: 存档(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;
}

最佳答案

https://uscilab.github.io/cereal/polymorphism.html

因为您没有对 cereal::base_class(this) 进行任何序列化,所以没有从您的派生类到基类的路径。尝试添加:

CEREAL_REGISTER_POLYMORPHIC_RELATION(基类,派生类一)CEREAL_REGISTER_POLYMORPHIC_RELATION(基类,尴尬派生类)

关于c++ - Cereal:序列化多态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34089699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com