c++ - 在类提升中序列化一个类

标签 c++ class boost-serialization

我尝试在 BOOST 的帮助下序列化一个类 MFace

// class of the face
class MFace
{
     public:
         //constructor
         MFace();
     private:

    //! Vector of the face nodes
        mymath::Vector<DG::MNode*> Nodes;

        friend class boost::serialization::access;
        template<class Archive>
            void serialize(Archive & ar, const unsigned int version){
                //! Vector of the face nodes
                ar & Nodes;
            }
 };

但该类包含另一个类

mymath::Vector<MNode*> Nodes;

所以,当我尝试将 Nodes 写入存档时

//create a face
MFace Face;

//archive output file
std::ofstream ofs("output.txt");
boost::archive::text_oarchive ar(ofs);
// Write data to archive
ar & Face;
    ...

编译器报错

error: ‘class mymath::Vector<DG::MNode*>’ has no member named ‘serialize’

我是否应该为 MFace 使用的每个类(特别是 mymath::Vector 和 MNodes)添加另一个“序列化”并描述它应该做什么,或者是否有可能在 MFace 中解决它而不触及其他类?

包括

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
//contains mymath::Vector<>
#include "mymath/vector.h"

//containes MNodes
#include "MNode.h"
#include <fstream>

最佳答案

如果我没记错我的 boost 序列化...

您可以在 MFace 的序列化方法中添加,如下所示:

void serialize(Archive & ar, const unsigned int version){
//of the face nodes
    for( <loop to travel through each node in the Nodes vector> )
    {
        ar & currentNode.var1;
        ar & currentNode.var2;
        ar & currentNode.var3;
    }
}

这是假设 Node 对象内部的每个成员都是 boost 库可以序列化的类型。

然而,这样做的问题是您将 MFace 类完全耦合到 MNode 类型 - 也就是说,如果您向 MNode 添加一个成员,则必须记住将其添加到 MFace 类的序列化中。

此外,如果您将任何类型的复杂对象添加到 boost 不知道如何序列化的 MFace 类,则您必须逐个序列化该成员。

每个对象的序列化最好知道如何序列化自身 - 如何序列化的定义应该包含在每个类的 serialize() 方法中。

如果将序列化方法添加到 DG::MNode 类,这个问题应该会消失。

关于c++ - 在类提升中序列化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341349/

相关文章:

c++ boost序列化类相互引用

c++ - qmake:将uic生成的头文件添加到安装目标

c++ - Windows 上的 Qt5 部署

python - 无意中绕过 Python 的私有(private)属性

ruby - 使用 `===`(包含运算符)比较类

c++ - 如何序列化 boost::function 以将其发送到 message_queue

c++ - 使用 boost 反序列化二进制数据时 static_assert 失败 "typex::value"失败

c++ - 反序列化表示非根表的 flatbuffers 二进制文件

c++ - 类型删除和可变参数模板化成员函数

javascript - 为什么我不能在 ES6 类中使用 let、const 或 var 关键字声明变量,但可以直接声明它?