如何在C++中序列化树结构?

sve*_*aro 6 c++ tree serialization

我正在尝试序列化/反序列化游戏场景,以便网络发送/接收和从/向磁盘保存/加载.

我的游戏引擎使用节点和组件,因此这些是唯一需要序列化的对象.场景可能如下所示:

Root Node
  - Node
    - SpecializedComponent
    - SpecializedComponent
    - Node 
      - Node
  - Node
    - Node
    - Node
      - Node
        - Node
          - SpecializedComponent
  - Node
Run Code Online (Sandbox Code Playgroud)

Node基本上是这样的:

class Node {
    map<String, Node> mChildren;
    map<String, Component> mComponents;
    uuid_t mId;
    Node* mParent;
};
Run Code Online (Sandbox Code Playgroud)

SpecializedComponent基本上是这样的:

class SpecializedComponent : public Component {
    uuid_t mId;
    Node* mNode;
};
Run Code Online (Sandbox Code Playgroud)

我想使用YAML或JSON作为我的文本表示.我有Qt,Boost和我想要的任何其他库,因此依赖性不是问题.实际上,节点已经是Q_OBJECTS所以我有反射.

尽管有反思,但将其正确地反序列化回C++树结构似乎是一个问题.

最理想的是,我想要一个优雅而有效的解决方案,将这样的结构序列化/反序列化为二进制或文本格式.

Cap*_*liC 3

下降递归解析器通常是处理重建部分的更简单且足够强大的选项。我可以尝试设置一些代码来具体显示,用伪代码表示如下:

 Node *parse(stream s) {
  content = new Node;
  s >> content >> nsons;
  for (int c = 0; c < nsons; ++c)
   content->addChild(parse(s));
  return content; 
 }
Run Code Online (Sandbox Code Playgroud)

当然,当读取组件时我们必须检查类型。