I'm looking for a way to write a tree so that it does not look ugly.
Let's say I have
1 2
|
struct Node{ /*abstract*/ };
struct Branch : Node{ std::vector< Node* > v; };
|
and several non abstract classes Apple, Banana, Candy : Node and Donkey, Elk : Branch.
Now I want a tree from these. The prettiest way I can think of is lisplike
my_tree = (Donkey Apple (Elk Banana) Candy) |
and etc. I can't think of a good way to get something like that in C++ though.
I could write
1 2
|
template<typename T>
Class& operator << (T t){ v.push_back( new T(t) ); return *this; }
|
for Class= every child of Branch (I'm only going to have a few of them, so I guess it's ok) and get
my_tree = Donkey() << Apple() << ( Elk() << Banana() ) << Candy(); |
which looks somewhat acceptable but does way too much copies.. (unless half of them are inlined..)
Or I could have a
1 2 3 4
|
struct List{
std::vector< Node* > v;
List& operator << ( Node* ) { ... }
};
|
and then write constructors Class( const List& ) for Class= every child of Branch. Then I'd have
my_tree = new Donkey( List() << new Apple() << new Elk( List() << new Banana() ) << new Candy() ); |
which takes care of the copies and the silly template, but I'm not sure if I like all the List() and new..
I'd appreciate any suggestions on how to write this neatly.