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.
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#.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With