1

I have some inherited classes:

struct BasicShape;

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

... and YAML file which contains the lines:

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

... which, obviously, represent different shapes with different options.

I'd like to convert the lines to instances of required classes. It's predictable, that I am using BasicShape * to handle everything I need.

Finally I ended up in writing 2 similar solutions:

Converting shapes instantly to the BasicShape *:

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

That was rejected later for it does not protect from memory leak.

Create a wrapper which delegates everything to pointer and destroy it if necessary:

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

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

Is there another better way to cope with the task?


I have found question "Can I read a file and construct hetereogenous objects at compile time?" and the answer is great, but I don't need all the flexibility of answer given. I believe that the solution could be simplified in my case with or without (that's preferable) using BOOST.

Community
  • 1
  • 1
Nick Roz
  • 3,918
  • 2
  • 36
  • 57

1 Answers1

0

Your second solution is the right way to go about this. yaml-cpp deals with value types only, so if you want any sort of inheritance, you'll need to manually wrap your polymorphic type in a value type, as you've done.

Jesse Beder
  • 33,081
  • 21
  • 109
  • 146