Template metaprogram converting type to unique number

后端 未结 9 955
小鲜肉
小鲜肉 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:18

    Similiar to Michael Anderson's approach but this implementation is fully standards compliant and can be performed at compile time. Beginning with C++17 it looks like constexpr values will be allowed to be used as a template parameter for other template meta programming purposes. Also unique_id_type can be compared with ==, !=, >, <, etc. for sorting purposes.

    // the type used to uniquely identify a list of template types
    typedef void (*unique_id_type)();
    
    // each instantiation of this template has its own static dummy function. The
    // address of this function is used to uniquely identify the list of types
    template 
    struct IdGen {
       static constexpr inline unique_id_type get_unique_id()
       {
          return &IdGen::dummy;
       }
    
    private:
       static void dummy(){};
    };
    

提交回复
热议问题