多语句lambdas的返回类型扣除 [英] Return type deduction with multi-statement lambdas

查看:142
本文介绍了多语句lambdas的返回类型扣除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写代码,我最近发现g ++不会警告我一个类的问题:per C ++ 11 5.1.2.4,如果你的lambda不是一个单一的return语句,然后返回类型必须声明为尾随返回类型或为void。

I've been writing code, and I've recently found out that g++ doesn't warn me about a certain class of issue: per C++11 5.1.2.4, if your lambda is not a single return statement then the return type must be declared as a trailing-return-type or be void.

尽管如果g ++足够有意义,但是允许编译无效的代码,要么关闭此行为(允许在g ++ - 4.7中使用 -fpedantic )或对此不起作用?

Although g++ is allowed to compile invalid code if it makes enough sense, is there a way to either turn this behavior off (allowed with -fpedantic in g++-4.7) or all least warn about it?

示例代码:

[]() { return 0; } //is fine
[&a]() { a++; return 0; } //is not fine but g++ doesn't warn me
[&a]() -> int {a++; return 0; } //is fine again

C ++ 11 5.1.2.4

C++11 5.1.2.4


一个实现不应该将rvalue引用类型的成员添加到闭包类型。
如果lambda表达式不包括lambda声明符,它就好像lambda声明符是()。如果一个lambda表达式不包括一个尾部返回类型,它就好像tail-return-type表示以下类型:

An implementation shall not add members of rvalue reference type to the closure type. If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:

- 如果复合 - 语句的格式为

{attribute-specifier-seq(opt)return expression; }

在左值到右值转换(4.1),数组到指针转换(4.2)和函数到指针转换(4.3)之后返回的表达式的类型;

— if the compound-statement is of the form
{ attribute-specifier-seq(opt) return expression ; }
the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);

- 否则为空。


推荐答案

是因为它是标准中的缺陷,并且将被更改(请参阅 DR 975 ):

That is because it is a defect in the standard, and will be changed (see DR 975):


975 lambdas退款类型扣款限制

975 Restrictions on return type deduction for lambdas

没有任何技术上的困难,
需要当前的限制,lambda的返回类型可以
只有当lambda的主体由一个单一的return
语句。特别是,多个返回语句可以是
,如果它们都返回相同的类型。

There does not appear to be any technical difficulty that would require the current restriction that the return type of a lambda can be deduced only if the body of the lambda consists of a single return statement. In particular, multiple return statements could be permitted if they all return the same type.

方法将其关闭。

这篇关于多语句lambdas的返回类型扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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