Note that there are some explanatory texts on larger screens.

plurals
  1. POMapping from character id to a class name in c++ via templates?
    text
    copied!<p>Duplicate: <a href="https://stackoverflow.com/questions/582331/c-is-there-a-way-to-instantiate-objects-from-a-string-holdig-their-class-name">Is there a way to instantiate objects from a string holding their class name? </a></p> <hr> <p>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.</p> <p>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().</p> <p>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').</p> <p>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?):</p> <pre><code>Msg * msg; switch(data[0]) { case 'A': msg = new A(); break; case 'B': msg = new B(); break; ... } msg-&gt;parse(data); </code></pre> <p>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.</p> <p><strong>NOTE</strong>: This seems like duplicate of <a href="https://stackoverflow.com/questions/582331/c-is-there-a-way-to-instantiate-objects-from-a-string-holdig-their-class-name">C++: Is there a way to instantiate objects from a string holdig their class name?</a> so I suggest to close this question.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload