Mastergeek
Mastergeek

Reputation: 429

c++ - Mapping a class to a string

Is it at all possible to map a class and/or its subclasses, like myClass, to a string/int/whatever?

This is what I'm thinking of:

map<myClass, string> myMap = {
    {subclass1, "one"},
    {subclass2, "two"}
    //etc etc
}

I'm having trouble compiling working sample code. Could I get some help with that?

Note: I'm using c++ 11

Upvotes: 0

Views: 216

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477060

You can use std::type_index for that:

#include <map>
#include <string>
#include <typeindex>

std::map<std::type_index, std::string> m { { typeid(myClass), "zero" }
                                         , { typeid(subclass1), "one" }
                                         , { typeid(subclass2), "two" }
                                         };

Upvotes: 4

Related Questions