Template metaprogram converting type to unique number

后端 未结 9 949
小鲜肉
小鲜肉 2020-12-03 03:37

I just started playing with metaprogramming and I am working on different tasks just to explore the domain. One of these was to generate a unique integer and map it to type,

9条回答
  •  离开以前
    2020-12-03 04:21

    type2int as compile time constant is impossible even in C++11. Maybe some rich guy should promise a reward for the anwser? Until then I'm using the following solution, which is basically equal to Matthew Herrmann's:

    class type2intbase {
        template 
        friend struct type2int;
    
        static const int next() {
            static int id = 0; return id++;
        }
    };
    
    template 
    struct type2int {
        static const int value() {
            static const int id = type2intbase::next(); return id;
        }
    };
    

    Note also

    template 
    struct type2ptr {
        static const void* const value() {
            return typeid(T).name();
        }
    };
    

提交回复
热议问题