Hi:
It might be a misuse of RTTI as I've read a few articles on RTTI, and they seem to tackle different issues from mine.
Here's my problem:
Let's say we've built a template class LinkedList<T>, which has a few member functions typical to a linked list, e.g. append(T t), addAt(T t, int index), etc
Now I want to build a console based interactive testing tool to test the template class LinkedList<T>.
Ideally, if I type --- LinkedList<int> int_list
the tool should create a linked list containing integers.
Likewise, if I type --- LinkedList<string> str_list
the tool should create a linked list containing strings.
If I further type --- str_list.append("first")
the tool should recognize the command and append it to the str_list.
In order to achieve that, the first thing I do is parse the command by the user, namely --- str_list.append("first")
I need to extract three signatures from the command:
1, which object is operated on?
2, which member function is called?
3, a parameter list containing all parameters entered into the tool by the user
Obviously, an intuitive approach is I write very similar code pieces for different types as determined at run time.
1 2 3 4 5 6 7 8 9 10 11
|
//pseudocode
if(run time type is int)
{
create and operate on LinkedList<int>;
}
else if(run time type is string)
{
create and operate on LinkedList<string>;
}
else if ...
...
|
Essentially, I'm exhausting a finite number of (basic) types in C++ (No need to worry about complex objects).
Personally, I think this is really an ugly solution.
Ideally, I want one piece of "template" code for all types, not many similar duplicated code pieces for different types.
I put a double quote on template because template is a compile time concept, while what I really need is a run time "template".
Is that possible? How can I possibly do that?
P.S. I've thought about implementing and using my own heterogeneous container. I might want to push linked lists of different types(LinkedList<int>, LinkedList<string>, etc) altogether into the container. Then I might want to process them differently by type. Again, this doesn't escape the duplicate code paradigm.
Please enlighten me!