Function returning a lambda expression

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.


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