#include<初始化列表>需要在基于范围的 for 中使用初始值设定项列表吗?初始化列表>
最终的 C++11 标准包括基于范围的 for 的规定,以便“仅适用于”本机数组,而无需包含
或任何其他标头。据我所知,这个问题首先在工作文件 n2900 作为 UK 78 和 79 评论的结果。
该提案还包含隐式 <code>#include 的规定每个翻译单元中的
#include <iostream>
int main()
{
for (auto i : { 1, 2, 3, 4, 5 })
std::cout << i << "\n";
}
不包含
,程序也将符合标准。
然而,当概念从 C++11 中删除时,基于范围的 for 被修改,如 n2930。虽然数组“正常工作”的规定仍然存在,但没有提及初始化列表也是如此;事实上,各种标准库容器标头将 #include
的规范和 8.5.4.2 的最终文本对我来说意味着相反的内容。
据我所知,这与该主题的最终措辞非常接近。那么,上面的程序是否符合最终标准,或者我是否需要 #include
甚至在基于范围的 for 中使用它?换句话说,在基于范围的 for 中使用初始化列表是否构成“std::initializer_list 的使用——甚至是类型未命名的隐式使用”(根据 8.5) .4.2 FDIS?
The final C++11 standard includes provisions for range-based for to "just work" for native arrays without having to include <iterator>
or any other header. This was addressed first, as far as I can tell, in working paper n2900 as a result of comments UK 78 and 79.
This proposal also included a provision to implicitly #include <initializer_list>
in every translation unit, so that e.g. the program
#include <iostream>
int main()
{
for (auto i : { 1, 2, 3, 4, 5 })
std::cout << i << "\n";
}
would be standard-conforming even without including <initializer_list>
.
However, when concepts were removed from C++11, range-based for was revised as seen in n2930. While the provision for arrays to "just work" remains, there is no mention that the same is true for initializer lists; indeed the specification that various standard library container headers will #include <initializer_list>
and the final text of 8.5.4.2 implies the opposite to me.
As far as I can tell, this is pretty close to the final wording on the topic. So, is the program above well-formed with regard to the final standard, or do I need to #include <initializer_list>
even to use it in a range-based for? Put another way, does the use of an initializer list in a range-based for constitute a "use of std::initializer_list
---even an implicit use in which the type is not named" per 8.5.4.2 of the FDIS?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会说是的。根据 §6.5.4[stmt.ranged]/1,该语句
相当于
和 这意味着使用
initializer_list
,并且
需要包含标题。I'd say yes. According to §6.5.4[stmt.ranged]/1, the statement
is just equivalent to
and that means an
initializer_list<int>
is used, and the<initializer_list>
header needs to be included.如果不包含
,GCC 7.1 会产生以下错误:要查看此错误,应省略
,因为包含会产生以下错误:
还将包括
。GCC 7.1 produces the following error if
<initializer_list>
is not included:To see this error one should omit
<iostream>
, because including<iostream>
will also include<initializer_list>
.