Compile-time constant id

前端 未结 16 2153
不知归路
不知归路 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:30

    If non-monotonous values and an intptr_t are acceptable:

    template
    struct TypeID
    {
    private:
        static char id_ref;
    public:
        static const intptr_t ID;
    };
    
    template
      char TypeID::id_ref;
    template
      const intptr_t TypeID::ID = (intptr_t)&TypeID::id_ref;
    

    If you must have ints, or must have monotonically incrementing values, I think using static constructors is the only way to go:

    // put this in a namespace
    extern int counter;
    
    template
    class Counter {
    private:
      Counter() {
        ID_val = counter++;
      }
      static Counter init;
      static int ID_val;
    public:
      static const int &ID;
    };
    
    template
      Counter Counter::init;
    template
      int Counter::ID_val;
    template
      const int &Counter::ID = Counter::ID_val;
    
    // in a non-header file somewhere
    int counter;
    

    Note that neither of these techniques is safe if you are sharing them between shared libraries and your application!

提交回复
热议问题