Function returning a lambda expression

Bartosz Milewski picture Bartosz Milewski · Jan 18, 2011 · Viewed 32.1k times · Source

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?

Answer

Sean picture Sean · Jan 18, 2011

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; };
}