c++ - How to extract derived classes from the base-class container? -


after storing objects of different types in same container using common parent class need extract them back.

[tests/test0.c++]:

int main() {     element wrapper;     wrapper.name = "div";     wrapper.attributes["id"] = "wrapper";      cargo<string> text("learn yesterday, live today, hope tomorrow.");      wrapper.children.push_back(&text);      cout << "name:\t"  << wrapper.name << endl;           /* have explicit cast here,           * can't used way           * since children may have different types           */     cout << "cargo:\t" << ((cargo< string >*) wrapper.children[0])->value << endl;      return 0; } 

[source/element.h]

struct element {     std::string name;     std::map< std::string, std::string > attributes;     std::vector< node* > children; }; 

[source/node.h]

struct node { }; 

[source/cargo.h]

template <typename type> struct cargo     : public node {     type value;      cargo(type value)         : value(value)     { } }; 

i need have kind of type holder associated real node type , use in farther casting-extracting operations... instead of hard-coded 1 in test.

update:

what i'm trying simple document object model data structure use symbol table entry xml-like language parser. don't want use existing xml library large. think idea of dom simple, can adopt more complex operations, example, allowing generic types nodes in dom tree using cargo<type>. recognize design adopted may not adequate! i'm open suggestions!

i thankful help!


question more design implementation.
although boost.variant , boost.any work, workaround. real problem may variable part of responsibility of classes, derived node class, not encapsulated.
try use composition instead. 1 host class used common interface , appropriate amount of components/delegates/whatever (those born solution design :) ).

or... totally different solution may fit you. may want venture meta programing word , ditch common interface. instead entities tuples (type lists) may of help.

best regards,
marcin


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -