C++匿名变量

Joh*_*ren 6 c++ c-preprocessor

为什么这不起作用?

 0. #define CONCAT(x, y) x ## y
 1. 
 2. #define VAR_LINE(x) \
 3.     int CONCAT(_anonymous, __LINE__) = x
 4. 
 5. #define VAR_LINE2(x) \
 6.     int _anonymous ## x = 1
 7.
 8. int main()
 9. {
10.     VAR_LINE(1);
11.     VAR_LINE(1);
12.     VAR_LINE(1);
13.     VAR_LINE2(__LINE__);
14. }
Run Code Online (Sandbox Code Playgroud)

上述宏观扩张的结果

int _anonymous__LINE__ = 1;
int _anonymous__LINE__ = 1;
int _anonymous__LINE__ = 1;
int _anonymous13 = 1;
Run Code Online (Sandbox Code Playgroud)

如果我不必将该__LINE__宏写为参数,那将会很方便.

我认为这个问题非常清楚.我希望能够生成匿名变量,以便在同一范围内声明多个变量时,此宏不会因重定义错误而失败.我的想法是使用预定义的__LINE__宏,因为不会像这样在同一行上声明变量.但宏观扩张困扰我,你能帮忙吗?

更新:正确答案

感谢Luc Touraille.但是,建议的解决方案存在一个小问题.操作数和##运算符之间必须有空格(显然标准说明不然,但如果运算符和操作数之间没有空格,则PS3风格的GCC不会正确扩展宏).

#define _CONCAT(x,y) x ## y
#define CONCAT(x,y) _CONCAT(x,y)
Run Code Online (Sandbox Code Playgroud)

VAR_LINE宏现在产生:

int _anonymous10 = 1;
int _anonymous11 = 1;
int _anonymous12 = 1;
Run Code Online (Sandbox Code Playgroud)

这已经过验证可以在Win32(Visual Studio 2008),XBOX360(Xenon)和PS3下运行.

Luc*_*lle 11

您需要添加一个间接级别,以便__LINE__扩展:

#define _CONCAT_(x,y) x ## y
#define CONCAT(x,y) _CONCAT_(x,y)

#define VAR_LINE(x) int CONCAT(_anonymous, __LINE__) = x
Run Code Online (Sandbox Code Playgroud)