c++ - 我可以有条件地使用超过 1 个参数吗?

标签 c++ parameters macros parameter-passing precompile

所以这段代码作为一个例子效果很好:

#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));
}

Live Example

但我想将它用于第二个参数,例如: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;
}

Working code online.

关于c++ - 我可以有条件地使用超过 1 个参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088482/

相关文章:

macros - 可以使用 destructuring-bind 定义 destructuring-setq 吗?

c++ - 非常具体的未解析外部符号 type_info::`vftable 在/NODEFAULTLIB 可执行文件中使用虚拟函数时

jquery - 在不重新加载页面的情况下删除 url 参数

java - Log4J2:替换参数无法正常工作

java - 更改 "File"参数的值而不创建类的新实例

c++ - 我们可以有递归宏吗?

scala - 在 Scala 宏中,如何获取类的完整 `extends` 子句?

c++ - 将 std::vector 复制到 boost::interprocess::vector

c++ - C++中的头文件

c++ - C++模板参数sizeof返回错误的结果