类函数宏的参数中是否允许使用预处理器指令?

Fra*_*eux 9 c++ language-lawyer c-preprocessor

这个问题涉及在类似函数的宏参数中使用预处理器指令的合法性。

考虑以下代码。#ifdef用于内部MY_MACRO参数:

#include <iostream>

// Macro to print a message along with the line number the macro appears at
#define MY_MACRO( msg ) { std::cerr << "Line " << __LINE__ << "\t- "<< msg << '\n'; }

int main()
{
    // Print the current build configuration
    MY_MACRO(
#ifdef NDEBUG // <-- preprocessor directive in macro argument
        "Release"
#else
        "Debug"
#endif
    )
}
Run Code Online (Sandbox Code Playgroud)

gcc 12 可以,msvc 19 不允许: https: //godbolt.org/z/G8j4aTG6j

标准对此有何规定?

Ted*_*gmo 6

简短回答:否

[cpp.replace.general]

由最外面的匹配括号界定的预处理标记序列形成了类函数宏的参数列表。列表中的各个参数由逗号预处理标记分​​隔,但匹配内括号之间的逗号预处理标记不会分隔参数。如果参数列表中存在预处理标记序列,否则这些预处理标记将充当预处理指令,则行为是未定义的

  • @FrançoisAndrieux 确实如此,问题和答案都更好。 (2认同)