简体   繁体   中英

Storing any type or struct in an std::map

I'm writing a topic-based publish/subscribe system in C++. My generic "Event" class has three parts:

  1. Event Type (std::string)
  2. Entity ID (unsigned int) - this is for the game engine
  3. Event Data (std::map<std::string, ???>)

To populate the "Event Data" map, I need to be able to store any data type or struct, like int, string, or Vector3 (struct), to give some examples. How can I do this? Or, maybe there is a better way to do this altogether...

On an unrelated note, is it better to use a char* or a string for event types and data names?

Tried boost:any ?

For your event types, why are you using a string? std::maps are stored sorted from lower to higher key value. This means that internally, you're going to be sorting strings. Try and keep it as simple as possible to start off with. Use an enum, which should make your maps that much faster, especially given they're going to be the foundation of a notification system.

Finally, you don't want to use char*, because the map will not work as you expect:

char* key1 = "Hi";
char* key2 = "Hi";
unsigned int id;
std::map< char* ,unsigned int > mymap;
mymap.insert( std::pair<char*,unsigned int>( key1, id ) );
mymap.insert( std::pair<char*,unsigned int>( key2, id ) ); //you've just created a duplicate entry

The reason is that key1 and key2 will have different addresses, even though they're the same string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM