C++ 17是否支持更简单的基于范围的For循环?

xml*_*lmx 28 c++ standards c++11

从C++ 11开始,我们可以写:

vector<int> v{1, 2, 3, 4};
for (auto x : v)
{
    cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)

根据Essentials of Modern C++ Style,以下代码很快在C++中也是合法的:

vector<int> v{1, 2, 3, 4};
for (x : v)
{
    cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)

这个功能是否可以在C++ 17或C++ 20中使用?

T.C*_*.C. 59

不,这是两年多前被委员会杀害的,主要是因为担心阴影引起的混乱:

std::vector<int> v = { 1, 2, 3, 4 };
int x = 0; 
for(x : v) {} // this declares a new x, and doesn't use x from the line above
assert(x == 0); // holds
Run Code Online (Sandbox Code Playgroud)

在整个委员会被拒绝的时候,Clang和GCC都已经实施了这一功能.最终实现了这些实现:Clang GCC

  • 嗯?https://cplusplus.github.io/EWG/ewg-active.html#81仍然开放,并说"作者将要修改". (3认同)
  • 哦......无论提案的优点如何,这都是非常不幸的.让这些列表保持最新非常重要. (3认同)
  • @hvd EWG问题列表在一年多的时间内未更新.IIRC STL没有积极致力于任何修订.无论如何,似乎很明显委员会不会接受任何在某种程度上与某种声明不相似的东西. (2认同)