Alexey Romanov
Alexey Romanov

Reputation: 170815

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

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.

Upvotes: 5

Views: 200

Answers (1)

catnip
catnip

Reputation: 25388

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.

Upvotes: 10

Related Questions