关于编译Lambda时报告返回的为void的错误

本文探讨了C++11中Lambda表达式的返回类型问题。具体地,当Lambda体仅包含单一返回语句时,编译器如何推断其返回类型。并给出了一种在Visual C++ 10编译器上避免特定错误的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


这个错误的信息是这样的:

a lambda that has been specified to have a void return type cannot return a value


报告错误的lambda的写法大概是这样:


[] (int a, int b){
    if (a<b)
        return true;
    else
        return false;
};



这个lambda在gcc下编译没有问题,在vc10下就会报上面的那个错误。


可以换成这种写法就OK了。


[](int a, int b){
    return a<b;
};

至于为什么,看这个解释:

The C++11 standard, §5.1.2/4 states:

If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:

  • If the compound-statement is of the form { 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);

  • otherwise, void.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值