将初始化列表传递给宏 [英] Passing an initialization list to a macro
问题描述
为什么下面的程序中的注释行不能编译?
Why doesn't the commented out line in the following program compile?
#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;
}
推荐答案
预处理器不知道 {}
初始化。它看到逗号,并认为这是新的宏参数的开始。然后下一个。它只知道方括号()
。
The preprocessor does not know about {}
initialisation. It sees the comma and thinks that's the start of a new macro argument. And then the next one. Only brackets ()
are things that it knows about.
[C ++ 11:16.3 / 11]:
由最外面的匹配括号界定的预处理标记序列形成了函数式宏的参数列表。列表中的各个参数由逗号预处理标记分隔,但匹配的内部括号之间的逗号预处理标记不会分隔参数。 [..]
[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. [..]
这篇关于将初始化列表传递给宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!