首页 > 解决方案 > 序列化 unordered_map 中的对象成员并存储到二进制文件中

问题描述

我正在制作一个多人游戏,服务器将它的游戏世界状态存储为一个名为 ServerWorldState 的类中的各种 std::unordered_map。

服务器由一个名为 Game 的类组成,其中包含 ServerWorldState。

目前我正在尝试制作 Save() 和 Load() 函数,现在它们将在 Game 类中。这些函数应该将 ServerWorldState 中的地图中的某些数据保存到二进制存档中,为此,我使用 Cereal 库进行序列化和标准文件 IO 流。

Cereal 需要一个序列化方法存在于一个类中,以便为序列化指定成员:

服务器世界状态.h

class ServerWorldState : public World
{
private:
    std::unordered_map<int, ServerProp> props;
public:
    template<class Archive>
    void serialize(Archive& archive);

};

服务器世界状态.cpp

template<class Archive>
void ServerWorldState::serialize(Archive& archive)
{
    archive(props); //Serialize things by passing them to the archive
}

ServerProp 类本身实际上还有另一个序列化方法。我不确定这对于更深入地指定应该序列化的对象成员是否正确。

游戏中的保存功能(加载工作非常相似并且有同样的问题,但由于我还没有完成它的设计,所以我只显示保存):

游戏.h

class Game
{
private:
    std::shared_ptr<ServerWorldState> currentWorld;
public:
    bool Save();
};

游戏.cpp

bool Game::Save()
{
    std::ofstream outfile("level.dat", std::ios::binary | std::ios::out);
    if (!outfile) {
        std::cout << "SERVER_WORLD_STATE::SAVE: Could not open world.dat file for saving!" << std::endl;
        return false;
    }

    {
        cereal::PortableBinaryOutputArchive oarchive(outfile); //Create an output archive

        oarchive(currentWorld); //Write data to the archive

    } //Archive goes out of scope, ensuring all contents are flushed

    outfile.close();

    return true;
}

本质上,我想序列化/反序列化和二进制保存/加载 ServerWorldState 中的 std::unordered_map,但我收到此链接错误:

错误 LNK2019 无法解析外部符号“public: void __cdecl ServerWorldState::serialize(class grain::PortableBinaryOutputArchive &)”(??$serialize@VPortableBinaryOutputArchive@cereal@@@ServerWorldState@@QEAAXAEAVPortableBinaryOutputArchive@cereal@@@Z) 在函数中引用公共:静态无效__cdecl谷物::访问::成员序列化(谷物类::PortableBinaryOutputArchive&,类ServerWorldState&)“(??$member_serialize@VPortableBinaryOutputArchive@cereal@@VServerWorldState@@@access@cereal@@SAXAEAVPortableBinaryOutputArchive@1@AEAVServerWorldState @@@Z) - Game.obj 第 1 行

我假设这将显示是否未定义序列化方法,但确实如此。我还认为我可能会遗漏一些内容,但我似乎一切都井井有条。

标签: c++binarysavecereal

解决方案


推荐阅读