I have the following preprocessor divective:
我有以下预处理器下潜:
#ifndef NDEBUG
#define TRACE printf
#else
#define TRACE(...)
#endif
and example of usage is:
用法的例子是:
TRACE("TRACE: some parameter = %i\n", param);
In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following:
在C中,当我构建调试版和发行版时,它们都能很好地工作,但是在C ++编译器中会发出以下内容:
warning: invalid character in macro parameter name
警告:宏参数名称中的无效字符
error: badly punctuated parameter list in `#define'
错误:`#define'中错误的标点参数列表
and points these warning and error to the 'TRACE(...)' directive.
并将这些警告和错误指向'TRACE(...)'指令。
How to write this in C++ correctly?
如何正确地用C ++写这个?
3 个解决方案
#1
1
You could do:
你可以这样做:
inline void TRACE(...) {}
#2
3
#define TRACE false ||
#define TRACE false ||
This turns TRACE(x,y,z) into false || (x,y,z). Since x,y and z will be expressions, (x,y,z) evaluates to z (comma operator). z must be a built-in type (to be legally passed to a printf-style function) so it should be valid on the right side of ||. It won't be evaluated, but it must be a legal expression (e.g. you can't reference class members which only exist in DEBUG builds)
这会将TRACE(x,y,z)变为false || (X,Y,Z)。由于x,y和z是表达式,(x,y,z)求值为z(逗号运算符)。 z必须是内置类型(合法地传递给printf样式函数),因此它应该在||的右侧有效。它不会被评估,但它必须是一个合法的表达式(例如,您不能引用仅存在于DEBUG构建中的类成员)
Vararg macros are a C99 invention, they're not in C++98 but might very well be in C++0x
Vararg宏是C99的发明,它们不在C ++ 98中,但很可能在C ++ 0x中
[edit] - Using || to guarantee non-evaluation
[编辑] - 使用||保证不评估
#3
0
What compiler? For what it's worth, G++ 4.3.1 does not have any problem with that code.
什么编译器?对于它的价值,G ++ 4.3.1对该代码没有任何问题。
#1
1
You could do:
你可以这样做:
inline void TRACE(...) {}
#2
3
#define TRACE false ||
#define TRACE false ||
This turns TRACE(x,y,z) into false || (x,y,z). Since x,y and z will be expressions, (x,y,z) evaluates to z (comma operator). z must be a built-in type (to be legally passed to a printf-style function) so it should be valid on the right side of ||. It won't be evaluated, but it must be a legal expression (e.g. you can't reference class members which only exist in DEBUG builds)
这会将TRACE(x,y,z)变为false || (X,Y,Z)。由于x,y和z是表达式,(x,y,z)求值为z(逗号运算符)。 z必须是内置类型(合法地传递给printf样式函数),因此它应该在||的右侧有效。它不会被评估,但它必须是一个合法的表达式(例如,您不能引用仅存在于DEBUG构建中的类成员)
Vararg macros are a C99 invention, they're not in C++98 but might very well be in C++0x
Vararg宏是C99的发明,它们不在C ++ 98中,但很可能在C ++ 0x中
[edit] - Using || to guarantee non-evaluation
[编辑] - 使用||保证不评估
#3
0
What compiler? For what it's worth, G++ 4.3.1 does not have any problem with that code.
什么编译器?对于它的价值,G ++ 4.3.1对该代码没有任何问题。