C++关于 lambda 表达式包含多条返回语句的问题

起因

在《C++ Primer 5th》中10.3.3节中提到一下例子:

//错误:不能推断lambda的返回类型
transform (vi.begin(), vi.end(), vi.begin(),
	[](int i){ if (i< 0) return -i; else return i; });

并表示:

但是,如果我们将程序改写为看起来是等价的 if 语句,就会产生编译错误。编译器推断这个版本的 lambda 返回类型为 void ,但它实际上返回了一个 int 值。

解决过程

在 stackoverflow 上查询相关问题,得到的回答是自从 C++14 后, lambda 表达式支持多条返回语句。

… the return type of the closure’s operator() is determined according to the following rules:

  • if the body consists of nothing but a single return statement with an expression, the return type is the type of the returned expression (after lvalue-to-rvalue, array-to-pointer, or function-to-pointer implicit conversion); otherwise, the return type is void. (until C++14)
  • The return type is deduced from return statements as if for a function whose return type is declared auto. (since C++14)

但是实际上在C++11标准的 gcc 和 clang 编译器上,上面例子的这条语句都通过了编译。

在这里插入图片描述
最后,我在 stackoverflow 上找到了答案

There’s no technical reason for this. IIRC it was already implemented by the GCC C++ maintainer and he said it’s trivial to implement.
The committee is very conservative about accepting features into the Standard so they went with this simple form of deduction and will later hopefully accept a more powerful form. See the reason for rejection on US 30 comment.
DR 975 is already marked “ready” so chances are good it will be accepted.

而且,题主还在后面补充了一个新内容 an official proposal for this extended return type deduction for all function types, and not only lambdas

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值