所以这段代码作为一个例子效果很好:
#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
,我得到错误:
error: invalid use of type
void
in parameter declaration
是否有一些允许我使用的 noop 参数类型?
最佳答案
您应该在宏中包含逗号,而不是发出 void。
#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;
}
关于c++ - 我可以有条件地使用超过 1 个参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088482/