Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based for loop without specifying variable type

I just discovered that this compiles fine with no error (gcc 5.3):

std::vector<whatever> vec;

for( e: vec )
  // do something

All the compiler does is issue this warning:

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

Could someone explain:

  • what that code does (is it only a way to assume auto without typing it, or is there more ?)
  • what c++1z is (I know c++11, c++14, never heard of c++1z...)
like image 433
kebs Avatar asked Jan 09 '16 19:01

kebs


1 Answers

The proposal (which hasn't been accepted, so it's not scheduled to become an official part of the language) was that when you omitted the type specifier, that the type specifier would be equivalent to auto &&, so your for loop would be equivalent to:

std::vector<whatever> vec;

for( auto &&e: vec )
  // do something

For further details, such as the motivation and specific effects on the (then current) standard, see the proposal, N3853.

For completeness: C++1z was a code-name for what became C++17. It came about rather accidentally: what became C++ 11 was referred to as "C++0x" for quite a while. When it was getting close to finished, people wanted a way to refer to the next version, so they incremented the x (which had originally just stood for "some unknown digit") to y. After that, obviously enough, came z, giving C++1z.

like image 129
Jerry Coffin Avatar answered Oct 29 '22 19:10

Jerry Coffin