Compile-time constant id

前端 未结 16 2190
不知归路
不知归路 2020-12-02 20:06

Given the following:

template
class A
{
public:
    static const unsigned int ID = ?;
};

I want ID to generate a unique c

16条回答
  •  臣服心动
    2020-12-02 20:28

    Here is a pragmatic solution, if you are ok with writing a single additional line DECLARE_ID(type) for each type you want to use:

     #include 
    
     template struct my_id_helper;
     #define DECLARE_ID(C) template<> struct my_id_helper { enum {value = __COUNTER__ }; }
    
     // actually declare ids:
     DECLARE_ID(int);
     DECLARE_ID(double);
     // this would result in a compile error: redefinition of struct my_id_helper’
     // DECLARE_ID(int);
    
     template
     class A
     {
     public:
         static const unsigned int ID = my_id_helper::value;
     };
    
     int main()
     {
         switch(A::ID)
         {
         case A::ID:    std::cout << "it's an int!\n"; break;
         case A::ID: std::cout << "it's a double!\n"; break;
         // case A::ID: // error: incomplete type ‘my_id_helper’
         default: std::cout << "it's something else\n"; break;
         }
     }
    

提交回复
热议问题