C ++匿名变量 [英] C++ anonymous variables

查看:94
本文介绍了C ++匿名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不起作用?

 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. }

上述宏扩展的结果

int _anonymous__LINE__ = 1;
int _anonymous__LINE__ = 1;
int _anonymous__LINE__ = 1;
int _anonymous13 = 1;

如果我不必写 __ LINE __ 宏作为参数。

It would be convenient if I didn't have to write that __LINE__ macro as an argument.

我认为问题很明显。我希望能够生成匿名变量,以便在声明同一范围内的多个变量时,该宏不会因重新定义错误而失败。我的想法是使用预定义的 __ LINE __ 宏,因为将不会像这样在同一行上声明任何变量。但是宏扩展使我感到困扰,您能帮忙吗?

I'm thinking the problem is pretty clear. I want to be able to generate anonymous variables so that this macro doesn't fail with redefinition error when declaring several variables within the same scope. My idea was to use the predefined __LINE__ macro because no variable will ever be declared on the same line like this. But the macro expansion troubles me, can you help?

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

Thanks to Luc Touraille. However, there was a tiny problem with the suggested solution. There has to be whitespace between the operands and the ## operator (apparently the standard says otherwise but the the PS3 flavoured GCC would not expand the macro properly if there were no whitespace between the operator and operands).

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

VAR_LINE宏现在产生:

The VAR_LINE macro now yields:

int _anonymous10 = 1;
int _anonymous11 = 1;
int _anonymous12 = 1;

已被验证可以在Win32(Visual Studio 2008),XBOX360(Xenon)和PS3下工作。

This has been verified to work under Win32 (Visual Studio 2008), XBOX360 (Xenon) and PS3.

推荐答案

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

You need to add a level of indirection so that __LINE__ will be expanded:

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

#define VAR_LINE(x) int CONCAT(_anonymous, __LINE__) = x

这篇关于C ++匿名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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