0

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

Mastergeek
  • 429
  • 1
  • 6
  • 16

1 Answers1

4

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" }
                                         };
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Awesome! This code works but how would I go about access the map? Attempting to pass the [] operator a class gives a ton of errors. – Mastergeek Sep 20 '13 at 21:30
  • 1
    @Mastergeek you pass a `typeid`, of course. However, note that the types involved [**need** to have virtual methods](http://stackoverflow.com/a/1986448/85371) for this to work at _runtime_: http://coliru.stacked-crooked.com/a/6dce760d9a52880c (see what happens if you remove the virtual destructor) – sehe Sep 20 '13 at 22:10
  • @Mastergeek: I think the page I linked to contains sufficient examples, non? – Kerrek SB Sep 20 '13 at 22:20
  • @sehe: `typeid` works on anything, but for references you only get *dynamic* lookup if the type is polymorphic. – Kerrek SB Sep 21 '13 at 19:05
  • @KerrekSB that's what I meant. "for _this_ to work" referred to what the OP was after. Also, I don't think "the type is polymorphic" has well-defined meaning (_static polymorphism_ anyone? In the words of ... someone else: "Types _aren't_ polymorphic. They're used _in polymorphic fashion_"). I prefer just saying "has a virtual member". – sehe Sep 21 '13 at 19:55
  • @sehe: I suppose I meant that the type [`std::is_polymorphic`](http://en.cppreference.com/w/cpp/types/is_polymorphic) :-) – Kerrek SB Sep 21 '13 at 20:57
  • 8
    @KerrekSB Oh hey. I need to learn the traits of the trick. Or the tricks of the trait. Wait. There's something punny in there. :/ Thanks – sehe Sep 21 '13 at 21:05
  • 2
    @sehe: When talking type punning is undefined behaviour. – Kerrek SB Sep 22 '13 at 16:59
  • Thanks all for the help. This is extremely useful for my project and I was very unsure how to do this. – Mastergeek Sep 22 '13 at 21:05