After storing objects of different types in the same container using common parent class I need to extract them back.
[Tests/test0.c++]:
int main()
{
element wrapper;
wrapper.name = "div";
wrapper.attributes["id"] = "wrapper";
cargo<string> text("Learn from yesterday, live for today, hope for tomorrow.");
wrapper.children.push_back(&text);
cout << "Name:\t" << wrapper.name << endl;
/* I have an explicit cast here,
* but it can't be used this 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 to have some kind of type holder to be associated with real node type and use it in farther casting-extracting operations... Instead of that hard-coded one in my test.
UPDATE:
What I'm trying to do is a simple Document Object Model Data structure to use it as symbol table entry for my xml-like language parser. I don't want to use any existing XML library as they are very large. I think the idea of DOM is simple, so I can easily adopt it for some more complex operations, for example, by allowing generic types for the nodes in DOM tree using cargo<Type>
. I recognize that the design I adopted may not be the most adequate! So I'm open to suggestions!
I would be thankful for any help!