C ++构造,其行为类似于__COUNTER__宏 [英] C++ construct that behaves like the __COUNTER__ macro
问题描述
我有一组C ++类,每个都必须声明一个唯一的顺序ID作为编译时常量。
为此,我使用 __ COUNTER __
内置宏,它转换为一个整数,每次出现时递增。 ids不需要遵循严格的顺序。唯一的要求是它们是顺序的,从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?
推荐答案
code> __ 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)
// ...
};
请参阅实例。
这篇关于C ++构造,其行为类似于__COUNTER__宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!