我希望能够动态创建一个唯一的变量名。
这是我的代码:
int call(int i)
{
return i;
}
#define XCAT3(a, b, c) a ## b ## c
#define CALL_2(arg, place, line) int XCAT3(cl, place, line) = call(arg);
#define CALL_1(arg) CALL_2(arg, __FUNCTION__, __LINE__)
int main(int argc, char* argv[])
{
CALL_1(1); /* this is line 20 */
return 0;
}
这在GCC中起作用 (http://ideone.com/p4BKQ),但不幸的是在Visual Studio 2010或2012中不起作用。
错误信息为:
test.cpp(20): error C2143: 语法错误: 缺少 ';' 在 'function_string'之前
test.cpp(20): error C2143: 语法错误: 缺少 ';' 在 'constant'之前
test.cpp(20): error C2106: '=': 左操作数必须是l值
如何在C++中创建即时唯一的变量名?
解决方案:
#define CAT2(a,b) a##b
#define CAT(a,b) CAT2(a,b)
#define UNIQUE_ID CAT(_uid_,__COUNTER__)
int main(int argc, char* argv[])
{
int UNIQUE_ID = 1;
int UNIQUE_ID = 2;
return 0;
}