auto 是基于范围的 for 循环中的可选关键字吗? [英] Is auto an optional keyword in ranged based for loops?

查看:22
本文介绍了auto 是基于范围的 for 循环中的可选关键字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得曾经有人告诉我,

I recall someone once telling me,

在基于范围的 for 循环中不需要 auto.它会如果我们要删除它,不要在语言中含糊不清."

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

这是真的吗?
下面的代码是有效的 C++ 语法吗?

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

for (elem : range){...}  

我认为这已经是有效的语法,但是当我去编译时
clang++ --std=c++1z,我看到以下错误:

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

编译器仍将其识别为基于范围的 for 循环,那么为什么它也不能派生类型?

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

推荐答案

The:

for (elem : range){...}  

语法当前无效,但有人提议使此语法有效,并且 gcc 5.2 支持该语法(现场观看):

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 )
    {
    }
}

如果我们在 C++14 模式下尝试这个,它会说:

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

警告:只提供没有类型说明符的基于范围的 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

所以这显然是可行的,并且已经在 gcc 中实现了.看起来这个特性在 gcc 6.0 中被移除了.

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

据我所知,这是在 gcc 中实现的,期望 提案 N3853:基于范围的 For-Loops:下一代 将被接受,但被拒绝,更新版本 N3994 说:

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:

这更新了 N3853(参见 [1]),它提出了语法for (elem :range)",通过添加对属性的支持并回答其他问题.请参阅原始提案以了解背后的原理此功能,这里不再赘述.

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.

我们可以看到它被 EWG 问题 81 我们也可以从 厄巴纳会议纪要.尽管该提案存在很多问题,但我相信 STL 在提案的问答部分提出了一组令人信服的论据,但我对提案被拒绝感到失望.

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.

这篇关于auto 是基于范围的 for 循环中的可选关键字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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