Creating macro using __LINE__ for different variable names(使用 __LINE__ 为不同的变量名创建宏)
问题描述
可能重复:
用##和创建C宏LINE(与定位宏的标记连接)
Possible Duplicate:
Creating C macro with ## and LINE (token concatenation with positioning macro)
我正在尝试使用 __LINE__ 宏来生成不同的变量名称.我有一个名为 Benchmark 的范围基准类(位于 utils 命名空间中),它的构造函数接受一个字符串.这是我创建的宏定义:
I am trying to use the __LINE__ macro to generate different variable names. I have a scoped benchmark class called Benchmark(located in the utils namespace) and it's constructor takes a string. Here is the macro definition I have created:
#define BENCHMARK_SCOPE utils::Benchmark bm##__LINE__(std::string(__FUNCTION__))
不幸的是,这会导致以下错误:
Unfortunately this causes the following error:
<some_file_name>(59):错误 C2374:'bm__LINE__':重新定义;多重初始化
这使我得出结论 __LINE__ 宏没有得到扩展.我根据这篇文章创建了我的宏.你知道为什么 __LINE__ 没有得到扩展吗?
This leads me to the conclusion the __LINE__ macros does not get expanded. I have created my macross according to this post. Do you have ideas why __LINE__ does not get expanded?
编辑:可能编译器信息也是相关的.我正在使用 Visual Studio 2010.
EDIT: probably the compiler info is also relevent. I am using visual studio 2010.
推荐答案
你需要使用2个宏的组合:
You need to use combination of 2 macros:
#define COMBINE1(X,Y) X##Y // helper macro
#define COMBINE(X,Y) COMBINE1(X,Y)
然后将其用作,
COMBINE(x,__LINE__);
这篇关于使用 __LINE__ 为不同的变量名创建宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 __LINE__ 为不同的变量名创建宏
基础教程推荐
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
