2016-11-17 84 views
2

我正在使用boost序列化来存储和加载几个类。我的目标是在一个包含其他类的类上使用序列化,因此其他类将被序列化。使用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>’ 
... 

有人能告诉我什么是错我的代码?我错过了什么吗? 我的代码是用于序列化派生和前向声明的类是否正确?

阿:

#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; 

/*....*/ 

} 

NB:载体m_Bvector可以包含B *或/和C *对象

了Bh:

#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; 

/*....*/ 

}

这是我的方法来调用保存和加载功能:

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; 
} 

/* ... */ 

回答

1

Boost需要知道类型是否是虚拟的(有任何虚拟方法,即通常使用vtable实现),因此它可以依靠typeiddynamic_cast来返回运行时保真度值。

您正试图在类型的定义可用之前实例化序列化机制(仅当前向声明时类型不完整),因此它不能生成序列化代码。

+0

我弄清楚为什么boost不能用我写的代码生成序列化代码。 但我尝试了几种方法来实现我的工作,但我没有这样做。 你有解决方案来使我的代码工作。 – stefhane

+0

欢迎使用stackoverflow。不要忘记[投票](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – sehe

+0

啊。评论中增加了一个问题。稍后我会看看 – sehe