使用Boost序列化向前声明类和继承
Use Boost serialization with forward declaration class and inheritance
我使用boost序列化来存储和加载几个类。我的目标是在一个包含其他类的类上使用序列化,这样其他类就会被序列化。
但是问题是这些类包含前向声明和继承,我不能对这些类进行boost序列化。
我在编译中有一个问题,特别是在前向声明上,有这些错误:
error: invalid use of incomplete type ‘class C’
error: forward declaration of ‘class C’
error: ‘value’ is not a member of ‘boost::is_polymorphic<C>’
...
谁能告诉我我的代码有什么问题?我错过什么了吗?我的代码序列化派生和前向声明类正确吗?A.h:
#include <boost/serialization/access.hpp>
#include <boost/serialization/vector.hpp>
class B;
class C;
class A {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & m_Bvector;
}
protected:
vector<B*> m_Bvector;
vector<C*> m_Cvector;
/*....*/
}
注意:m_Bvector可以包含B*或/和C*对象
B.h:
#include <boost/serialization/access.hpp>
#include "A.h"
class B {
private :
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & m_someInt;
}
protected :
int m_someInt;
/*....*/
}
刘昀:
#include <boost/serialization/base_object.hpp>
#include "B.h"
classe C : public B {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & boost::serialization::base_object<B>(*this);
ar & m_someOtherInt;
}
protected:
int m_someOtherInt;
/*....*/
}
这是我调用save和load函数的方法:
SerializationManager.h:
#include <A.h>
#include <C.h>
#include <boost/serialization/export.h>
BOOST_CLASS_EXPORT(C);
class SerializationManager {
/*....*/
public:
bool save(string filename);
bool load(string filename);
protected:
A* m_classToSave;
}
SerializationManager.cpp:
#include "SerializationManager.h"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
#include <sstream>
bool SerializationManager::save(string filemname)
{
std::ofstream outputFile(filemname);
assert(outputFile.good());
boost::archive::text_oarchive oTextArchive(outputFile);
oTextArchive << m_classToSave;
return true;
}
bool SerializationManager::load(string filename)
{
delete m_classToSave;
std::ifstream ifs( filename );
assert(ifs.good());
boost::archive::text_iarchive ia(ifs);
// restore the schedule from the archive
ia >> m_classToSave;
return true;
}
/* ... */
Boost需要知道类型是否是虚拟的(有任何虚拟方法,即通常用虚函数表实现),所以它可以依靠typeid
和dynamic_cast
返回运行时保真度值。
您试图在类型定义可用之前实例化序列化机制(仅前声明类型是不完整的),因此它无法生成序列化代码。
相关文章:
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 如何在QT Creator上将QWidget声明为继承类的对象
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 在使用受保护和继承时无法访问在类中声明的私有成员
- C++ 声明继承的构造函数?
- C++具有继承列表的模板声明
- 如何对继承的文件使用前向声明
- 抽象类 A 由类 C 继承"through"类 B "intermediary"。如何声明虚拟功能?
- 有什么理由在没有继承的情况下声明一个虚拟方法
- 具有继承的未声明标识符(运算符 ostream)
- 为什么使用声明不会继承移动构造函数
- 带有递归继承和使用声明的Variadic模板
- 带有智能指针和继承的构造函数的前向声明
- 声明从C 中的其他类模板继承的类模板
- 错误 - 根据 G++ 未声明的继承类字段
- 在C 中使用继承时,请避免使用未缴纳的函数声明/定义
- 来自无法识别的继承结构的本地声明
- C++ 嵌套前向声明继承
- clang/g++ 与私有继承和使用声明的区别