基于范围的for循环,无需指定变量类型 [英] Range-based for loop without specifying variable type

查看:114
本文介绍了基于范围的for循环,无需指定变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现它可以正常编译且没有错误(gcc 5.3):

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:


警告:基于范围的for循环,没有类型说明符,仅可用于-std = c ++ 1z或-std = gnu ++ 1z

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

有人可以解释一下:


  • 代码的作用(只是假设 auto 而不输入它的一种方法,还是还有其他方法?)

  • c ++ 1z是什么(我知道c ++ 11,c ++ 14,从未听说过c ++ 1z ...)

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

推荐答案

提案(尚未接受,因此未计划成为该语言的正式组成部分)是当您省略类型说明符,该类型说明符将等效于 auto&& ,因此您的for循环等效于:

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

有关进一步的详细信息,例如对(当时的)当前标准的动机和特定影响,请参阅提案 N3853

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

出于完整性考虑:C ++ 1z是代码-成为C ++ 17的名称。它是很偶然地发生的:很长一段时间以来,后来成为C ++ 11的东西都被称为 C ++ 0x。当它接近完成时,人们想要一种方法来引用 next 版本,因此他们增加了 x (最初只是表示 <未知数字)到 y 。之后,很明显,出现了 z ,得到了 C ++ 1z

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.

这篇关于基于范围的for循环,无需指定变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆