c++ - 序列化 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 行
我假设这将显示是否未定义序列化方法,但确实如此。我还认为我可能会遗漏一些内容,但我似乎一切都井井有条。
解决方案
推荐阅读
- python - 如何模拟每个方法测试的类初始化程序?
- react-native - 将登录数据访问 redux 存储到不同的组件中
- arrays - 无法将 sql 行添加到节点 js 中的 javascript 数组中
- jquery - Jquery显示/隐藏问题
- python - 如何删除所有嵌套的 JSON 对象?
- reactjs - 不能在 Render 之外的函数中使用 this.props 或设置 this.state
- r - !is_num 中的错误:无效的参数类型 - 在尝试使用交互项进行线性回归的情况下,这意味着什么?
- excel - VBA - 如果不满足条件,则停止整个脚本运行
- mysql - 当表在 SQL 中没有值时,有没有办法让值显示在运行总计中
- python - 我的 python 脚本中的问题在哪里?