【发布时间】:2015-05-25 08:53:00
【问题描述】:
我有一些继承的类:
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 */ };
}
还有其他更好的方法来处理这项任务吗?
我找到了问题“Can I read a file and construct hetereogenous objects at compile time?”,答案很好,但我不需要给出答案的所有灵活性。我相信在我的情况下,无论是否使用(最好)使用 BOOST,解决方案都可以简化。
【问题讨论】:
标签: c++ inheritance yaml yaml-cpp