• 0

[C++] Map strings to class types?


Question

This has been stumping me rather thoroughly for a good portion of the day today so I'd appreciate it if anyone can offer any help.

I basically need to be able to create a new instance of an arbitrary class using a string assigned to be its name. An example of what I'd like to be able to do is:

SomeBaseType *x = new mapStringObjectName["someClassNameString"]; //mapStringObjectName is std::map<string, ?not sure what this one should be?>

I've tried a bunch of different ways to do this and I'm trying to avoid having to just make a large switch statement to do this, but its just eluding me.

For example, "document" would create an instance of CDocument and "someotherthing" would create an instance of COtherThing, both of those would derive from CObject.

I'm thinking I may need each derivative to have its own CreateInstanceOfMe function to be called and a static initializer to add itself to the map but I'm not sure how to go about that.

Link to comment
https://www.neowin.net/forum/topic/964230-c-map-strings-to-class-types/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Unfortunaly types do not exist at run-time in C++. There's some limited, optional, reflection (RTTI) but it won't help you solve the problem you're having.

I've recently devised a similar system where I wanted to map integers to types and have a specific processing function for each of these types. I used boost::signal to get C#-like events but I think that's an unecessary layer.

You still have to do the mapping manually but a map is better than a switch statement IMO.

I have to go so I'll just shoot the code and I'll explain in more detail later if needed. It was a system for exchanging data over TCP (hence the references to sockets). Keep in mind it's probably too complex for your needs, but you can probably take some ideas from that and make your own system.

enum MessageID { S_LOGIN_ACCEPTED, S_LOGIN_REFUSED, etc. };
std::map<MessageID, boost::function<void ()> > m_processMessage;

template<typename MessageType>
void BindEvent(MessageID id, boost::signal<void (MessageType&)>* Event)
{
	m_processMessage[id] = boost::bind(&ClientSocket::OnMsg<MessageType>, this, Event);
}
// OnMsg is basically a factory method, in our case it had to create the object from the TCP input buffer
template<typename T>
void OnMsg(boost::signal<void (T&)>* signal) {
     T message;
     // deserialize message from buffer
     (*signal)(message);
}
// Now how this worked is that a function would look at the first four bytes in the input buffer, interpret it as an integer (MessageID) and call the correctly typed OnMsg through the map:
MessageID messageID = *(MessageID*)m_inputBuffer;
m_processMessage[messageID]();

// So now you just need to call BindEvent for each pair [id, event], we had code like
BindEvent(S_LOGIN_ACCEPTED, &m_communicationsManager->Evt_LoginAccepted);
BindEvent(S_LOGIN_REFUSED, &m_communicationsManager->Evt_LoginRefused);
// where m_communicationsManager was a class responsible for exposing all TCP messages as events (boost::signal)
// example:
boost::signal<void (Msg_S_LoginAccepted&)> Evt_LoginAccepted;
boost::signal<void (Msg_S_LoginRefused&)> Evt_LoginRefused;

// And there you got your mapping, from id (MessageID) to type (Msg_S_LoginAccepted, etc.). You'll need to adapt the example for your purposes
// because you probably don't need events, but it's touchy so I don't have time to produce a simplified sample right now.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Seem like they are seeking for a one size fits all. You have power users and "what's a computer" generation growing up on phones, tablets, and Chromebooks.
    • Guessing it was profitable enough inserting prompted apps vs the hate it generated.
    • Also good for Debugging or troubleshooting your game.. i dont get it why nvidia app or amd does not show this data.. if steam can do it..
    • Microsoft reportedly planning to lay off thousands of employees, mostly in sales by Usama Jawad Back in May 2025, Microsoft decided to lay off 3% of its workforce, which amounted to roughly 6,000 employees. It claimed that this decision allowed it to implement better organizational changes in a "dynamic marketplace". Now, a new report claims that the Redmond tech firm is planning to lay off thousands more next month. Citing unnamed sources, Bloomberg reports that as the company continues investing heavily in its AI ventures, it is about to announce layoffs of thousands of workers as early as next month. This reduction in workforce will primarily affect sales teams, but they won't be the only ones affected. That said, the sources did mention that the timing for this announcement may change. This move, if true, won't be entirely surprising. In April 2025, Microsoft announced that it will be relying more on third-party firms to sell its software to small- and medium-sized customers. It's currently unclear how many employees will be impacted by this change, but even if the layoff percentage is in the single digits, it would still be significant as it would be impacting the professional careers of thousands. The May 2025 layoffs primarily impacted engineering and product teams. The other major round of layoffs prior to this was the decision to eliminate 10,000 jobs back in January 2023. Those represented 5% of the total workforce at that time, with numerous teams, including the one leading Mixed Reality (MR) efforts, being heavily impacted. It is interesting to note that if the timing of the announcement for layoffs is accurate, it would be soon after Microsoft closes its fiscal year at the end of June 2025. Although we'll get financial reports for the latest quarter soon after too, one has to wonder what the human cost of profit is, as Microsoft continues to report billions of dollars in revenue every quarter. Source: Bloomberg (paywall)
  • Recent Achievements

    • First Post
      Fuzz_c earned a badge
      First Post
    • First Post
      TIGOSS earned a badge
      First Post
    • Week One Done
      slackerzz earned a badge
      Week One Done
    • Week One Done
      vivetool earned a badge
      Week One Done
    • Reacting Well
      pnajbar earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      704
    2. 2
      ATLien_0
      285
    3. 3
      Michael Scrip
      213
    4. 4
      +FloatingFatMan
      194
    5. 5
      Steven P.
      131
  • Tell a friend

    Love Neowin? Tell a friend!