Function returning a lambda expression
Solution 1
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; };
}
Solution 2
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.
Solution 3
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.
Solution 4
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;};
};
Solution 5
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);
Bartosz Milewski
Lapsed theoretical physicist turned programmer. Lapsed C++ programmer turned Haskell programmer. Interested in category theory and functional programming.
Updated on July 08, 2022Comments
-
Bartosz Milewski almost 2 years
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?
-
Maxim Egorushkin over 13 yearsThat is going to cause a memory allocation though in the constructor of
std::function
. -
snk_kid over 13 years@Maxim Yegorushkin std::function has move semantics plus it can use custom allocators and the C++0x working draft has these notes: "[Note: implementations are encouraged to avoid the use of dynamically allocated memory for small callable objects, for example, where f’s target is an object holding only a pointer or reference to an object and a member function pointer. —end note ]" so basically you can not make many assumptions as to what allocation strategy a particular implementation is using but you should be able to use your own (pooled) allocators anyway.
-
Maxim Egorushkin over 13 years@Sean: you could as well wrap it into boost::any. The question was how to specify the return type. This answer sidesteps the question.
-
Sean over 13 years@Maxim: My answer was to the question "Is the only solution handcrafting a function object and returning it?"
-
Bartosz Milewski over 13 yearsThis sounds right. Unfortunately, it doesn't work with the current compiler I'm using: VS 2010. std::function conversion happens to work.
-
Ben Voigt over 12 yearsYes, the final wording of this rule came too late for VC2010.
-
jfs over 12 yearsI've added code example. Here's a full program.
-
Flexo over 12 years@J.F.Sebastian - What's the lifetime of the lambda in this example? Is it long enough to outlive the result of the conversion to function pointer?
-
jfs over 12 years@awoodland: Good question. The code does what the words in the answer say. Whether it is correct I don't know. The full program I've linked above works with gcc.
-
Flexo over 12 years@J.F.Sebastian - I can't seem to find an answer to that so I've asked it as a question in its own right: stackoverflow.com/questions/8026170/…
-
Bartosz Milewski over 12 yearsThat's only true when the outer lambda consists of just the return statement. Otherwise you have to specify the return type.
-
robson3.14 almost 12 yearsThis is the best answer as it doesn't require runtime polymorphism of std::function and allows for lambda to have a non-empty capture list, however I would use const auto fun = ...
-
sehe almost 8 yearsWhy mention c++14's deduced types but omit polymorphic lambdas?
auto retFun() { return [](auto const& x) { return x; }; }
-
Anthony Hall over 7 yearsJust keep in mind that
std::function
employs type erasure, which can mean the cost of making a virtual function call when calling thestd::function
. Something to be aware of if the returned function is going to be used in a tight inner loop or other context where the slight inefficiency matter. -
dzhioev about 6 years@BartoszMilewski not true since C++14.
-
Ad N over 2 yearsHow does this code compile if you do not have c++11? (lambdas are since c++11)