Compile-time constant id

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

    I encountered this exact problem recently. My solution:

    counter.hpp

    class counter
    {
        static int i;
        static nexti()
        {
            return i++;
        }
    };
    

    Counter.cpp:

    int counter::i = 0;
    

    templateclass.hpp

    #include "counter.hpp"
    
        template 
        tclass
        {
            static const int id;
        };
    
        template 
        int tclass::id = counter::nexti();
    

    It appers to work properly in MSVC and GCC, with the one exception that you can't use it in a switch statement.

    For various reasons I actually went further, and defined a preprocessor macro that creates a new class from a given name parameter with a static ID (as above) that derives from a common base.

提交回复
热议问题