Use data type (class type) as key in a map

前端 未结 3 1985
轮回少年
轮回少年 2020-12-13 18:02

I have class Base and classes Derived_1, Derived_2 ... I need derived classes to have an id. Those ids are used for further lookups et

3条回答
  •  我在风中等你
    2020-12-13 18:40

    C++11 solves this by providing std::type_index, in , which is a copyable, comparable and hashable object constructed from a std::type_info object that can be used as the key in associative containers.

    (The implementation is fairly simple, so even if you don't have C++11 yourself, you could steal the implementation from, say GCC 4.7, and use that in your own code.)

    #include 
    #include 
    #include 
    
    typedef std::unordered_map tmap;
    
    int main()
    {
        tmap m;
        m[typeid(main)] = 12;
        m[typeid(tmap)] = 15;
    }
    

提交回复
热议问题