Preprocessor counter macro

痞子三分冷 提交于 2019-12-30 09:20:17

问题


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?

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.

Example:

#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;
}

Expected output:

TEST0 
TEST1    

回答1:


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.



来源:https://stackoverflow.com/questions/22332103/preprocessor-counter-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!