111

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. 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) 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. 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

117

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; };
}
Sign up to request clarification or add additional context in comments.

5 Comments

That is going to cause a memory allocation though in the constructor of std::function.
@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.
@Sean: you could as well wrap it into boost::any. The question was how to specify the return type. This answer sidesteps the question.
@Maxim: My answer was to the question "Is the only solution handcrafting a function object and returning it?"
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.
32

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 Comment

Why mention c++14's deduced types but omit polymorphic lambdas? auto retFun() { return [](auto const& x) { return x; }; }
32

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 Comments

This sounds right. Unfortunately, it doesn't work with the current compiler I'm using: VS 2010. std::function conversion happens to work.
Yes, the final wording of this rule came too late for VC2010.
I've added code example. Here's a full program.
@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?
@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/…
|
25

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 Comments

That's only true when the outer lambda consists of just the return statement. Otherwise you have to specify the return type.
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 = ...
@BartoszMilewski not true since C++14.
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);

Comments

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 Comment

How does this code compile if you do not have c++11? (lambdas are since c++11)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.