C++ construct that behaves like the __COUNTER__ macro(行为类似于 __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++ 构造


- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01