使用 YAML C++ 加载继承的对象

Loading inherited objects with YAML C++

我继承了一些类:

struct BasicShape;

struct Circle : BasicShape;
struct NGon : BasicShape;
struct Star : NGon;
struct Triangle : NGon;

... 和包含以下行的 YAML 文件:

shapes:
  small_circle: [circle, 5]
  big_circle: [circle, 8]
  star7: [ngon, 7, 3]

...这显然代表具有不同选项的不同形状。

我想将这些行转换为所需 类 的实例。可以预见,我正在使用 BasicShape * 来处理我需要的一切。

最后我写了 2 个类似的解决方案:

立即将形状转换为 BasicShape *:

namespace YAML {
  template<> struct convert<BasicShape *> { /* code goes here */ };
}

后来被拒绝了,因为它不能防止内存泄漏。

创建一个包装器,将所有内容委托给指针并在必要时销毁它:

struct Shape {
  BasicShape * basic_shape;
  /* code goes here */
};

namespace YAML {
  template<> struct convert<Shape> { /* code goes here */ };
}

有没有其他更好的方法来应对这个任务?


我找到了问题“Can I read a file and construct hetereogenous objects at compile time?”,答案很好,但我不需要给出答案的所有灵活性。我相信在我的情况下,无论是否使用 BOOST(最好),解决方案都可以得到简化。

你的第二个解决方案是解决这个问题的正确方法。 yaml-cpp 只处理 值类型 ,所以如果你想要任何类型的继承,你需要手动将你的多态类型包装在一个值类型中,就像你所做的那样。