Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return one of two (or more) lambdas in C++

Tags:

c++

lambda

Since C++ lambdas have unique unnamed types, something like this doesn't work:

auto select_lambda() {
    if (someCondition())
        return []() { return 1; };
    else
        return []() { return 2; };
}

They can be wrapped into an std::function:

std::function<int()> select_lambda() { /* same body */ }

But this has a significant overhead. Is there a better way to achieve something similar? I had some preliminary ideas but none which I got working yet.

like image 789
Alexey Romanov Avatar asked May 21 '21 22:05

Alexey Romanov


People also ask

How do you declare a lambda function in C?

C# language specification. See also. You use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body. A lambda expression can be of any of the following two forms: Expression lambda that has an expression as its body: C#.

How to deduce the return type of a lambda expression?

The return type of a lambda expression is automatically deduced. You don't have to use the auto keyword unless you specify a trailing-return-type. The trailing-return-type resembles the return-type part of an ordinary method or function.

What is the Lambda body of a lambda expression?

The lambda body of a lambda expression is a compound statement. It can contain anything that's allowed in the body of an ordinary function or member function. The body of both an ordinary function and a lambda expression can access these kinds of variables: Captured variables from the enclosing scope, as described previously. Parameters.

Is it possible to call a lambda expression multiple times?

This seems impossible, because when you define the lambda expression, you can provide only one operator (): This lambda has only one way of calling it: You pass an integer and it returns an integer. But it turns out that you can create a lambda that can be called in multiple ways: Use an auto parameter!


1 Answers

If your lambdas don't need to capture anything then you can prepend + to each of them to convert them to a regular function pointer:

auto select_lambda() {
    if (someCondition())
        return +[]() { return 1; };
    else
        return +[]() { return 2; };
}

If you need capturing lambdas then std::function would seem to be the best way to go.

like image 119
Paul Sanders Avatar answered Oct 19 '22 05:10

Paul Sanders