我有一些继承的类:
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 *
来处理我需要的一切。
最后,我最终编写了两个类似的解决方案:
立即将形状转换为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 */ };
}
还有另一种更好的方法来应对这项任务吗?
我找到问题&#34; Can I read a file and construct hetereogenous objects at compile time?&#34;答案很好,但我不需要给出答案的所有灵活性。我相信使用BOOST可以在有或没有(最好是)的情况下简化解决方案。
答案 0 :(得分:0)
你的第二个解决方案是正确的方法。 yaml-cpp只处理值类型,所以如果你想要任何类型的继承,你需要像你一样手动将你的多态类型包装在一个值类型中。