函数返回一个 lambda 表达式

我想知道是否有可能在 C + + 11中编写一个返回 lambda 函数的函数。当然,一个问题是如何声明这样的函数。每个 lambda 都有一个类型,但是这个类型在 C + + 中是不可表达的。我不认为这会起作用:

auto retFun() -> decltype ([](int x) -> int)
{
return [](int x) { return x; }
}

还有这个:

int(int) retFun();

我不知道任何从 lambdas 到函数指针之类的自动转换。唯一的解决方案是手工创建一个函数对象并返回它吗?

44003 次浏览

You don't need a handcrafted function object, just use std::function, to which lambda functions are convertible:

This example returns the integer identity function:

std::function<int (int)> retFun() {
return [](int x) { return x; };
}

For this simple example, you don't need std::function.

From standard §5.1.2/6:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

Because your function doesn't have a capture, it means that the lambda can be converted to a pointer to function of type int (*)(int):

typedef int (*identity_t)(int); // works with gcc
identity_t retFun() {
return [](int x) { return x; };
}

That's my understanding, correct me if I'm wrong.

You can return lambda function from other lambda function, since you should not explicitly specify return type of lambda function. Just write something like that in global scope:

 auto retFun = []() {
return [](int x) {return x;};
};

Though the question specifically asks about C++11, for the sake of others who stumble upon this and have access to a C++14 compiler, C++14 now allows deduced return types for ordinary functions. So the example in the question can be adjusted just to work as desired simply by dropping the -> decltype... clause after the function parameter list:

auto retFun()
{
return [](int x) { return x; }
}

Note, however, that this will not work if more than one return <lambda>; appears in the function. This is because a restriction on return type deduction is that all return statements must return expressions of the same type, but every lambda object is given its own unique type by the compiler, so the return <lambda>; expressions will each have a different type.

You should write like this:

auto returnFunction = [](int x){
return [&x](){
return x;
}();
};

to get your return as a function, and use it like:

int val = returnFunction(someNumber);

If you do not have c++ 11 and are running your c++ code on micro controllers for example. You can return a void pointer and then perform a cast.

void* functionThatReturnsLambda()
{
void(*someMethod)();


// your lambda
someMethod = []() {


// code of lambda


};


return someMethod;
}




int main(int argc, char* argv[])
{


void* myLambdaRaw = functionThatReturnsLambda();


// cast it
auto myLambda = (void(*)())myLambdaRaw;


// execute lambda
myLambda();
}