所以这段代码很适合作为例子:
#ifdef DEBUG
#define DECLARE_DEBUG_PARAM(x) x
#define PASS_DEBUG_PARAM(x) x
#else
#define DECLARE_DEBUG_PARAM(x) void
#define PASS_DEBUG_PARAM(x)
#endif
int foo(DECLARE_DEBUG_PARAM(const bool param)) {
#ifdef DEBUG
if(param) {
cout << "DEBUG true\n";
} else {
cout << "DEBUG false\n";
}
#else
cout << "RETAIL\n";
#endif
}
int main() {
foo(PASS_DEBUG_PARAM(true));
}
但是我想将它用于第二个参数,例如:int foo(const int param1, DECLARE_DEBUG_PARAM(const int param2))
显然,对于我当前对DECLARE_DEBUG_PARAM
的定义不起作用,我得到错误:
错误:在参数声明
中无效使用类型void
是否有一些我可以使用的noop参数类型允许这个?
答案 0 :(得分:1)
你应该在宏中包含逗号,而不是发出空白。
#ifdef DEBUG
#define DECLARE_DEBUG_PARAM(x) , x
#else
#define DECLARE_DEBUG_PARAM(x)
#endif
int foo(const int param1 DECLARE_DEBUG_PARAM(const int param2))
或在逗号中包含逗号,因此可以在任何地方使用此宏:
#ifdef DEBUG
#define DECLARE_DEBUG_PARAM(...) __VA_ARGS__
#define PASS_DEBUG_PARAM(...) __VA_ARGS__
#else
#define DECLARE_DEBUG_PARAM(...)
#define PASS_DEBUG_PARAM(...)
#endif
int foo1(DECLARE_DEBUG_PARAM(const bool param)) {
#ifdef DEBUG
if(param) {
cout << "DEBUG true\n";
} else {
cout << "DEBUG false\n";
}
#else
cout << "RETAIL\n";
#endif
}
int foo2(int DECLARE_DEBUG_PARAM(, const bool param)) {
#ifdef DEBUG
if(param) {
cout << "DEBUG true\n";
} else {
cout << "DEBUG false\n";
}
#else
cout << "RETAIL\n";
#endif
}
int main() {
foo1(PASS_DEBUG_PARAM(true));
foo2(0 PASS_DEBUG_PARAM(,true));
return 0;
}
答案 1 :(得分:1)
我会建议一些不同的选择。
1)使用默认值:
enum class DebugSwitch {No_debug, Debug}
void function(int param1, DebugSwitch debug_param = DebugSwitch::No_debug)
{...}
2)使用参数对象
struct Parameters
{
int param1;
bool debug_param;
// ....
};
void function(Parameter& p)
{
///...
}
为什么呢?您正在将可以发送到函数的值的可能组合的数量相乘;
DEBUG defined + param == true
DEBUG defined + param == false
DEBUG not defined + param == true
DEBUG not defined + param == false
确保您正确处理所有组合 - 减少“转向”变量的数量。
答案 2 :(得分:0)
引用C ++ FAQ:
因为
#define
宏以四种不同的方式是邪恶的:evil#1,evil#2,evil#3和evil#4。有时你应该使用它们,但它们仍然是邪恶的。
在这里使用宏是没有意义的。它只是#ifdef
代码,但需要用户查看。更好的方法就是使用#ifdef
:
int foo(
#ifdef DEBUG
const bool param
#endif
);
int foo(const int param1
#ifdef DEBUG
, const int param2
#endif
);
要打电话做同样的事情:
foo(
#ifdef DEBUG
true
#endif
);
foo(13
#ifdef DEBUG
, 42
#endif
);
对于使用少量参数的函数,此代码可能有点不稳定,如果认为更具可读性,则可以使用#else
进行布局:
#ifdef DEBUG
int foo(const bool param);
#else
int foo();
#endif
#ifdef DEBUG
int foo(const int param1, const int param2);
#else
int foo(const int param1);
#endif
对于这些电话可以做同样的事情:
#ifdef DEBUG
foo(true);
#else
foo();
#endif
#ifdef DEBUG
foo(13, 42);
#else
foo(13);
#endif