gpt4 book ai didi

c++ - STL 中令人烦恼的解析 scott meyers

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:25 29 4
gpt4 key购买 nike

我正在关注 Item6,它是 Scott Meyers 着的 Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library 中最令人烦恼的解析。

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

我的问题是作者的以下陈述是什么意思? “用圆括号包围形式参数声明是不合法的,但是用圆括号包围函数调用的参数是合法的”

谢谢

最佳答案

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++ 的最令人烦恼的解析:任何可以被解释为声明的东西都将被解释为声明。


正如 this comment 中所建议的那样通过 StoryTeller ,从 C++11 开始,您可以使用花括号初始化代替:

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

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

关于c++ - STL 中令人烦恼的解析 scott meyers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570644/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com