108

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?

6
  • 1
    To add what's already been said, stateless lambda functions are convertible to function pointers.
    – snk_kid
    Commented Jan 18, 2011 at 18:57
  • 3
    IMO your first option won't work since the lambda in the decltype isn't the same as in the function body and therefore has a different type (even if you included the return statement)
    – Motti
    Commented Jan 18, 2011 at 21:06
  • 1
    By the way, if a lambda has an empty capture clause, it can be implicitly convertible to a pointer to function.
    – GManNickG
    Commented Jan 18, 2011 at 21:15
  • @GMan: Unless you are using Visual C++ 2010 or a version of g++ released more than about a year ago (or thereabouts). The captureless-lambda implicit conversion to function pointer wasn't added until March 2010 in N3092. Commented Jan 19, 2011 at 1:43
  • 4
    Lambda expressions in general cannot appear in unevaluated operands. So decltype([](){}) or sizeof([]() {}) is ill-formed no matter where you write it. Commented Feb 16, 2011 at 1:05

6 Answers 6

112

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; };
}
5
  • 7
    That is going to cause a memory allocation though in the constructor of std::function. Commented Jan 18, 2011 at 21:11
  • 2
    @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.
    – snk_kid
    Commented Jan 18, 2011 at 23:58
  • @Sean: you could as well wrap it into boost::any. The question was how to specify the return type. This answer sidesteps the question. Commented Jan 19, 2011 at 9:36
  • 1
    @Maxim: My answer was to the question "Is the only solution handcrafting a function object and returning it?"
    – Sean
    Commented Jan 19, 2011 at 18:11
  • 4
    Just keep in mind that std::function employs type erasure, which can mean the cost of making a virtual function call when calling the std::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. Commented Dec 17, 2016 at 6:05
31

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.

6
  • 1
    This sounds right. Unfortunately, it doesn't work with the current compiler I'm using: VS 2010. std::function conversion happens to work. Commented Jan 23, 2011 at 20:44
  • 3
    Yes, the final wording of this rule came too late for VC2010.
    – Ben Voigt
    Commented Nov 5, 2011 at 17:32
  • I've added code example. Here's a full program.
    – jfs
    Commented Nov 5, 2011 at 23:47
  • @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?
    – Flexo
    Commented Nov 6, 2011 at 0:12
  • 1
    @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/…
    – Flexo
    Commented Nov 6, 2011 at 9:30
30

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.

1
  • 5
    Why mention c++14's deduced types but omit polymorphic lambdas? auto retFun() { return [](auto const& x) { return x; }; }
    – sehe
    Commented Jun 22, 2016 at 20:52
24

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;};
 };
3
  • 3
    That's only true when the outer lambda consists of just the return statement. Otherwise you have to specify the return type. Commented Dec 16, 2011 at 18:59
  • 3
    This 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 = ...
    – robson3.14
    Commented Jul 14, 2012 at 15:30
  • 4
    @BartoszMilewski not true since C++14.
    – dzhioev
    Commented Apr 19, 2018 at 7:33
1

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);
0

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();
}
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.