STL 中令人烦恼的解析 scott meyers

vexing parse in STL scott meyers

我正在关注 Item6,它是 Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library 作者 Scott Meyers。

ifstream dataFile("ints.dat");
list<int> data(istream_iterator<int>(dataFile), // warning! this doesn't do
               istream_iterator<int>()); // what you think it does

所有这些都很有趣(以其自身扭曲的方式),但它并不能帮助我们说出我们想说的,即列表对象应该用文件的内容初始化。现在我们知道我们必须打败什么解析,这很容易表达。用圆括号包围形式参数声明是不合法的,但是用圆括号包围函数调用的参数是合法的,所以通过添加一对圆括号,我们强制编译器以我们的方式看待事物:

list<int> data((istream_iterator<int>(dataFile)), // note new parens
                istream_iterator<int>0); // around first argument
                                         // to list's constructor

我的问题是作者的以下陈述是什么意思? "It's not legal to surround a formal parameter declaration with parentheses, but it is legal to sur-round an argument to a function call with parentheses"

谢谢

What does author mean by following statement? It's not legal to surround a formal parameter declaration with parentheses, but it is legal to sur-round an argument to a function call with parentheses

Scott Meyers 所说的是,通过用括号将函数调用的参数括起来,它只能是 函数调用 不是一个函数声明,因为后者是非法的(即:排除了作为函数声明的可能性)。

否则,如果两者都是合法的,它将被解释为函数声明。这是因为 C++ 最令人烦恼的解析:任何可以解释为声明的东西都将被解释为声明。


正如 by StoryTeller 中已经建议的那样,从 C++11 开始,您可以使用 大括号初始化 代替:

ifstream dataFile("ints.dat");
list<int> data{istream_iterator<int>(dataFile), istream_iterator<int>()}; 
上面的

data 不会被解释为函数声明,因为函数声明中不允许使用大括号。