Compile-time constant id

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

    Using this constant expression counter:

    template 
    class A
    {
    public:
        static constexpr int ID() { return next(); }
    };
    class DUMMY { };
    int main() {
        std::cout << A::ID() << std::endl;
        std::cout << A::ID() << std::endl;
        std::cout << A::ID() << std::endl;
        std::cout << A::ID() << std::endl;
        return 0;
    }
    

    output: (GCC, C++14)

    1
    2
    3
    3
    

    The downside is you will need to guess an upper bound on the number of derived classes for the constant expression counter to work.

提交回复
热议问题