• 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

    • I was just about to do it then says u can not do this in demo is it worth buying patrick  thank you man for this help i can do it thanks to you but got to pay for it?
    • Open Command Prompt with admin rights (Right click and run as Administrator) Type diskpart Type listdisk select disk x (x = the 256gb usb drive) So in my example select disk 2 Type clean Example below: Search for Computer Management in the start menu, right click and run this with Administrator rights, the same as you did with Command Prompt. Go to Disk Management and right click on the USB drive. Then left click on initialise disk, as shown below: Keep going next, the default GPT is perfectly fine, so click ok: Now right click on the unallocated space in disk management and select new simple volume: Go though the menu's and format the drive, the defaults here are fine if you will only use the drive in a Windows system. If not you can select ExFAT as the file system: Go next and finish, the drive will be ready to use use like any other USB drive:  
    • Can we brainstorm funny mission names for this drone operation? Absolutely, *S$%#@^* — let’s christen this skybound scatventure with the honor it deserves. Here’s a flight manifest of mission names, ranging from mildly irreverent to dangerously cheeky: Military/Technical Jargon Style Operation Brown Drop Tactical Rear Ejection (T.R.E.) Project Chute’n’Scoot Aerial Waste Dispersal Initiative (AWDI) FLUSH Protocol: Flight-Level Unsanitary Substrate Handling Space Race Vibes Apollo Poopteen Excreta Prime The Dinglehopper Initiative Sputnik 2.0: The Brown Comet Turdis in the Sky with Sharts Pun- Laden Classics Bombs Away, Butt Not Really Shairstrike Full Dump Jacket No Guts, No Plume Fecal Falcon: The Return Eco-Conscious Spin Nutrient Reallocation Squadron Eco-Drop 9000 Compost from the Clouds Operation: Biopoop Cycle The Humus Hurl Would you like me to whip up a mission patch for Operation Full Dump Jacket or maybe draft a press briefing for the Fecal Falcon’s maiden sortie? We can even simulate a malfunction scenario — “Code Brown in Sector 12!” Where to next, Flight Commander?   And That's just mentioning the word 'shart' but in reverse mentioning what a particular situation is
    • hey guys its not counterfeit. i did test its ok needs formatting but how do i do that i need to go in dos and disk Disk Management anyone know step by step please 
    • The first link on the github page gives me a very, very red page warning me about phishing........
  • 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
      713
    2. 2
      ATLien_0
      279
    3. 3
      Michael Scrip
      209
    4. 4
      +FloatingFatMan
      201
    5. 5
      Steven P.
      132
  • Tell a friend

    Love Neowin? Tell a friend!