C++17 会支持更简单的基于范围的 For 循环吗?
Will C++17 support the simpler Range-based For Loop?
从 C++11 开始,我们可以这样写:
vector<int> v{1, 2, 3, 4};
for (auto x : v)
{
cout << x << endl;
}
根据Essentials of Modern C++ Style,以下代码很快也将在 C++ 中合法:
vector<int> v{1, 2, 3, 4};
for (x : v)
{
cout << x << endl;
}
此功能在 C++17 或 C++20 中可用吗?
Update
GCC 5.1 allows this syntax with -std=c++1z.
This is not allowed anymore since GCC 6.1.
So this answer doesn't seem to be correct.
Ideone 编译器在 C++ 14 下成功编译了这样的代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v {1, 2, 3, 4};
for (x : v)
cout << x << endl;
return 0;
}
没有。这被委员会否决了 more than two years ago,主要是因为担心隐藏可能造成的混淆:
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
反对意见在此过程中出现得太晚,以至于 Clang 和 GCC 在被全体委员会否决时都已经实施了该功能。实施最终被取消:Clang GCC
这还是an open issue. There was a proposal, linked there, to add this to C++17. That proposal was rejected。新提案是否会被接受取决于提案,所以现在说 C++20 是否有它还为时过早。
从 C++11 开始,我们可以这样写:
vector<int> v{1, 2, 3, 4};
for (auto x : v)
{
cout << x << endl;
}
根据Essentials of Modern C++ Style,以下代码很快也将在 C++ 中合法:
vector<int> v{1, 2, 3, 4};
for (x : v)
{
cout << x << endl;
}
此功能在 C++17 或 C++20 中可用吗?
Update
GCC 5.1 allows this syntax with -std=c++1z.
This is not allowed anymore since GCC 6.1.So this answer doesn't seem to be correct.
Ideone 编译器在 C++ 14 下成功编译了这样的代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v {1, 2, 3, 4};
for (x : v)
cout << x << endl;
return 0;
}
没有。这被委员会否决了 more than two years ago,主要是因为担心隐藏可能造成的混淆:
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
反对意见在此过程中出现得太晚,以至于 Clang 和 GCC 在被全体委员会否决时都已经实施了该功能。实施最终被取消:Clang GCC
这还是an open issue. There was a proposal, linked there, to add this to C++17. That proposal was rejected。新提案是否会被接受取决于提案,所以现在说 C++20 是否有它还为时过早。