Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

c++ - Is auto an optional keyword in ranged based for loops?

I recall someone once telling me,

"there is no need for auto inside range-based for loops. It would not be ambiguous in the language if we were to remove it."

Is that a true statement?
Is the folowing code valid C++ syntax?

for (elem : range){...}  

I had assumed this was already valid syntax, but when I went to compile with
clang++ --std=c++1z, I was shown the following error:

range-based for loop requires type for loop variable
 for (elem: range){

The compiler still recognizes this as a range-based for loop, so why can't it also derive the type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The:

for (elem : range){...}  

syntax is not currently valid but there was a proposal to make this valid syntax and the syntax is supported in gcc 5.2 (see it live):

#include <vector>

int main()
{
    std::vector<int> v ;

    for( elem : v )
    {
    }
}

and if we try this in C++14 mode it says:

warning: range-based for loop without a type-specifier only available with -std=c++1z or -std=gnu++1z

So this would clearly work and has been implemented in gcc. It looks like this feature was removed in gcc 6.0.

As far as I can tell this was implemented in gcc with the expectation that proposal N3853: Range-Based For-Loops: The Next Generation would be accepted but it was rejected and the updated version N3994 says:

This updates N3853 (see [1]) which proposed the syntax "for (elem : range)", by adding support for attributes and answering additional questions. Please see the original proposal for the rationale behind this feature, which is not repeated here.

We can see it was rejected from the EWG issue 81 and we can also see this from the Urbana meeting minutes. Although there are many issues with the proposal I believe STL made a convincing set of arguments in the Question and Answers section of the proposal and I was disappointed that the proposal was rejected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...