行为类似于 __COUNTER__ 宏的 C++ 构造

我有一组 C++ 类,每个类都必须声明一个唯一的顺序 id 作为编译时常量.为此,我使用了 __COUNTER__ 内置宏,它转换为一个整数,每次出现时都会递增.id 不需要遵循严格的顺序.唯一的要求是它们是顺序的,并且从 0 开始:

I have a set of C++ classes and each one must declare a unique sequential id as a compile-time constant. For that I'm using the __COUNTER__ built-in macro which translates to an integer that is incremented for every occurrence of it. The ids need not to follow a strict order. The only requirement is that they are sequential and start from 0:

class A {
public:
    enum { id = __COUNTER__ };
};

class B {
public:
    enum { id = __COUNTER__ };
};

// etcetera ...

我的问题是:有没有办法使用 C++ 构造(例如模板)实现相同的结果?

My question is: Is there a way to achieve the same result using a C++ construct, such as templates?

推荐答案

这是使用 __LINE__ 宏和模板的可能方法:

Here is a possible way to do it using __LINE__ macro and templates:

template <int>
struct Inc
{
    enum { value = 0 };
};

template <int index>
struct Id
{
    enum { value = Id<index - 1>::value + Inc<index - 1>::value };
};

template <>
struct Id<0>
{
    enum { value = 0 };
};

#define CLASS_DECLARATION(Class) 
template <> 
struct Inc<__LINE__> 
{ 
    enum { value = 1 }; 
}; 
 
struct Class 
{ 
    enum { id = Id<__LINE__>::value }; 
private:

使用示例:

CLASS_DECLARATION(A)
    // ...
};

CLASS_DECLARATION(B)
    // ...
};

CLASS_DECLARATION(C)
    // ...
};

查看现场示例.

相关文章