将初始化列表传递给宏

Passing an initialization list to a macro

为什么下面程序中被注释掉的行不能编译?

#include <iostream>
#include <vector>
using namespace std;

#define F1(a) 1

int F2(vector<int>) { return 2; }

int main() {
    vector<int> v;
    v = vector<int>{1,2,3};

    cout << F1( v ) << endl;
    //The following line doesn't compile. The error is:
    //error: macro "F" passed 3 arguments, but takes just 1
    //cout << F1( vector<int>{1,2,3} ) << endl; // <- error!
    cout << F1( vector<int>({1,2,3}) ) << endl;
    cout << F1( (vector<int>{1,2,3}) ) << endl;

    cout << F2( v ) << endl;
    //The following line compiles fine
    cout << F2( vector<int>{1,2,3} ) << endl;
    cout << F2( vector<int>({1,2,3}) ) << endl;
    cout << F2( (vector<int>{1,2,3}) ) << endl;

    return 0;
}

预处理器不知道 {} 初始化。它看到逗号并认为这是新宏参数的开始。然后是下一个。只有括号 () 是它知道的东西。

[C++11: 16.3/11]: The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. [..]

宏不是函数。它将您的输入 vector<int>{1,2,3} 解释为 3 个输入,即 vector<int>{123}。您可以通过将其设为表达式 (vector<int>{1,2,3}) 来更改它(就像您已经做的那样)。

括号中的所有内容都是一个表达式并且vector<int>(...)是一个(*特殊成员-)函数,因此预处理器将其视为一个表达式

另一种解决方法是将您的 MACRO 转换为 variadic MACRO

#define F1(...) 1

或者在更一般的情况下;转:

#define M(a) a

进入这个:

#define M(...) __VA_ARGS__