lambda函数返回一个auto类型的函数,编译错误C/C++ code#includestdio.hint main(void){auto closure[](
lambda函数返回一个auto类型的函数,编译错误
- C/C++ code
#include<stdio.h>int main(void){ auto closure=[](){ int a=0; return [&](){ printf("%d\n",++a);};//这行编译错误 }; closure(); return 0;}在VC2010下面编译不过,提示a lambda that has been specified to have a void return type cannot return a value
这是什么意思呢? 我的代码如何改才能正确?
[解决办法]
auto closure=[](){
这个lambda函数没有声明返回类型 所以是void的 不能在内部return值
[解决办法]
又仔细看了一下 这段程序有几个问题:
1. 外边那个lambda没有声明返回值,不能return。应该改成[]()->std::function<void()> {...
2. 你是想把那个有printf的lambda返回给closure吧。这样的写法closure被赋予的是外边那个lambda而不是里面return的那个。应该在外边的lambda声明的最后分号的前面加上()表示函数调用。
3. 内部的lambda访问了外边lambda的本地变量a,而这个lambda被调用时无法访问相同的环境,行为未定义。
改正了1和2的代码如下
- C/C++ code
#include <functional>#include <stdio.h>int main(void){ auto closure=[]()->std::function<void()> { int a=0; return [&](){ printf("%d\n",++a); }; }(); closure(); return 0;}
[解决办法]
你这个就像 void f(){ return 1;}一个道理。
[解决办法]
VC2010中lambda表达式返回类型的自动推导经常抽风,时好时坏,有毛病时就显式指定返回值好了。
[解决办法]
ISO C++11
5.4.2/4
4 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:
— if the compound-statement is of the form
{ attribute-specifier-seqoptreturn 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.
[ Example:
auto x1 = [](int i){ return i; }; // OK: return type is int
auto x2 = []{ return { 1, 2 }; }; // error: the return type is void (a
// braced-init-list is not an expression)
—end example ]
[解决办法]
