c++ boost::serialization 为类设置固定的 class_id

标签 c++ serialization boost

我使用 boost 来序列化和反序列化一些类

像这样:

boost::archive::xml_oarchive xmlArchive(oStringStream);

xmlArchive.register_type(static_cast<BaseMessage *>(NULL));
xmlArchive.register_type(static_cast<IncomingTradeMessage *>(NULL));
xmlArchive.register_type(static_cast<InternalRequestInfo *>(NULL));
xmlArchive.register_type(static_cast<InternalTradeTransInfo *>(NULL));

const BaseMessage* myMessage =message;

xmlArchive << make_nvp("Message", myMessage);

现在我的类根据使用的顺序获得一个class_id,我不想要这样,我想控制Class_id的

所以我可以做类似的事情

BOOST_SET_CLASS_ID(1234, BaseMessage);

在我的项目中,BaseMessage 的所有位置的 class_id 都是 1234。

我怎样才能做这样的事情

最佳答案

你不能使用BOOST_CLASS_EXPORT_GUID或类似的东西吗?即

BOOST_CLASS_EXPORT_GUID(IncomingTradeMessage, "IncomingTradeMessage")
...

由于传输字符串而不是整数,它将使用更多带宽,但它会解决您的问题。

引用thisthis了解更多信息。

编辑:

这个编译得很好:

#include <fstream>
#include <boost/serialization/export.hpp>
#include <boost/archive/text_oarchive.hpp>

class Foo {
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & dummy1;
    }

    int dummy1;

public:
    virtual ~Foo() {}
};

class Bar : public Foo {
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        // serialize base class information
        ar & boost::serialization::base_object<Foo>(*this);
        ar & dummy2;
    }

    int dummy2;
};

BOOST_CLASS_EXPORT_GUID(Foo, "Foo")
BOOST_CLASS_EXPORT_GUID(Bar, "Bar")

int main(int argc, char *argv[]) {
    std::ofstream ofs("filename");
    boost::archive::text_oarchive oa(ofs);
    Foo *f = new Bar;
    oa << f;

    return 0;
}

关于c++ boost::serialization 为类设置固定的 class_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3148794/

相关文章:

c++ - 是否可以实现仅 header 的非模板类?

java - 无法从 START_OBJECT token 中反序列化 'java.util.date' 的实例

c++ - Qt Linux 中的链接 boost

c++ - Qt 项目中对 boost::system::generic_category() 的 undefined reference

c++ - 构建libssh时在qt和cmake错误上找不到libssh的功能

c++ - 如何检查是否单击了 QPushButton

c++ - Qt Creator - 如何编写 UI?

c# - 如何序列化 Windows.Media.Brush

java - ObjectInputStream/ObjectOutputStream 工作不正常

c++ - 如何在 GNU Autotools 项目中包含 Boost?