Duplicate: Is there a way to instantiate objects from a string holding their class name?
Is there a (better) way in C++ to map string id to a class name. I suspect there might be a way via templates but I wasn’t able to figure out the correct way.
For example if I have multiple messages, each storing in the first byte a character id. So message A12345 would instantiate class A() message B12345 would map to class B().
I have a group of message parsers where each class can parse give message. The issue is that I have to manually generate mapping between class that parses given message (e.g. class A()) and the message id (e.g. the ‘A’).
This is what I’m doing in the code now, and I’m thinking if there’s a nice way to eliminate the switch in c++ (templates magic?):
Msg * msg;
switch(data[0])
{
case 'A': msg = new A(); break;
case 'B': msg = new B(); break;
...
}
msg->parse(data);
On the side note, most of the time the id’s are actually 2 character long so ‘A1’ ‘B1’ and so on. And I’m using the class names the same to keep track of the classes, e.g. ‘A1’ can be parsed by class A1() and so on.
NOTE: This seems like duplicate of C++: Is there a way to instantiate objects from a string holdig their class name? so I suggest to close this question.
As someone else said, it can’t be done using templates (templates are computed at compile time. But your character id is compute at runtime).
You can use a map from id to constructor function. It boils down to this question: Instantiate objects from a String holding their class name
I recommend you to keep it simple. If a plain switch will do it, keep it that way. If you later really need to have it extensible, you can still introduce some automatic look-up of character ids and so on.