预处理器计数器宏 [英] Preprocessor counter macro

查看:115
本文介绍了预处理器计数器宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法创建一个 COUNTER()宏(遵循C ++ 11/14标准),扩展为一个数字,每增加​​一个时间 COUNTER()是否被调用?

Is there a way to create a COUNTER() macro (which follows the C++11/14 standard) that is expanded to a number which increases by one every time COUNTER() is invoked?

我想过了,使它工作。我没有找到在 COUNTER()宏中存储state的方法。

I've thought about it, but couldn't find a way to make it work. I didn't find a way to store "state" in the COUNTER() macro.

示例:

#define COUNTER() <...> // Implementation goes here...
#define UNIQUE_NAME_1() TEST ## COUNTER()
#define UNIQUE_NAME_2() TEST ## COUNTER()

// Note how the COUNTER() macro can be used with other macros
// (it cannot be implemented with C++ code)

int main() {
    std::cout << STRINGIFY(UNIQUE_NAME_1()) << std::endl;
    std::cout << STRINGIFY(UNIQUE_NAME_2()) << std::endl;
}






TEST0 
TEST1    


推荐答案

GCC和我相信VC ++都提供了 __ COUNTER __ 宏,这是做你期望的。我不知道它遵循标准,但它可能足够接近现实世界的使用。

GCC, and (I believe) VC++ both provide the __COUNTER__ macro, which does about what you'd expect. I don't know that it follows the standard exactly, but it's probably close enough for real-world use.

这篇关于预处理器计数器宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆