Range-based for loop without specifying variable type

时光总嘲笑我的痴心妄想 提交于 2020-04-07 02:36:51

问题


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...)

回答1:


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.



来源:https://stackoverflow.com/questions/34697639/range-based-for-loop-without-specifying-variable-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!