Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning a lambda expression

I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:

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

Nor this:

int(int) retFun(); 

I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it?

like image 828
Bartosz Milewski Avatar asked Jan 18 '11 17:01

Bartosz Milewski


People also ask

Can you return a lambda function?

The lambda function can take many arguments but can return only one expression.

What is the return type of lambda?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.

What is a lambda function in C++?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.


1 Answers

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; }; } 
like image 140
Sean Avatar answered Sep 19 '22 23:09

Sean