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

C++ construct that behaves like the __COUNTER__ macro(行为类似于 __COUNTER__ 宏的 C++ 构造)

本文介绍了行为类似于 __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)
    // ...
};

查看现场示例.

这篇关于行为类似于 __COUNTER__ 宏的 C++ 构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:行为类似于 __COUNTER__ 宏的 C++ 构造

基础教程推荐