Roman Holiday
Roman Holiday

Reputation: 109

Forward declaration for recursive data structure

Way back when I was writing Delphi, there was a TStringList which was basically a map of strings to Delphi's generic TObject. Using this structure, I could easily make a recursive, hierarchical structure by placing another TStringList against one of the string keys:

ParentStringList["somekey"] = "just a string value";
ParentStringList["anotherkey"] = SomeChildStringList;

Question is, how do I achieve the same thing in C++?

What I have at the moment is:

typedef boost::variant< std::string, my_dictionary > my_variant;
typedef std::map < std::string, my_variant > my_dictionary;

... which is clearly circular.

Can I do this without wrapping things in structs (which I can forward declare), or without using pointers (which the compiler knows the size of)?

Upvotes: 4

Views: 398

Answers (3)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

This approach could work:

struct my_variant;
typedef map<string,my_variant> my_dict;
struct my_variant: variant<string, my_dict>
{};

There are a few issues with it though:

  • This requires containers (std::map specifically) that allow template arguments that are not fully defined. Using C++98, this is explicitly forbidden, I'm not sure if this was lifted in later C++ versions.
  • Publicly deriving from containers is not usually a good idea, please research the reasons for that yourself and how they apply to your program. Using containment instead of derivation would be a safer alternative, or the middle way of private derivation, but that breaks the useful IS-A relationship that this approach provides.

Upvotes: 0

user1973385
user1973385

Reputation: 155

Try using vectors. I've used them before as internal representations of an external database within my program as a data structure.

Upvotes: -2

erenon
erenon

Reputation: 19118

The Boost.Variant documentation covers this exact case. You can't do it without using pointers or some other similar wrapper.

Upvotes: 3

Related Questions