mardi 12 novembre 2019

Why does capturing a variable make the type of a lambda unique?

In the following minimal example:

int main()
{
    const int foo = 1;
    const auto a = foo == 1 ? [](){return 42;} : [](){return 4;};
    const auto b = foo == 1 ? [foo](){return 42;} : [foo](){return 4;};
}

a is fine. b however is not, because:

<source>:5:29: error: incompatible operand types ('(lambda at <source>:5:31)' and '(lambda at <source>:5:53)')

    const auto b = foo == 1 ? [foo](){return 42;} : [foo](){return 4;};
                            ^ ~~~~~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~

Why is that the case? And how can the intended b be obtained?

Aucun commentaire:

Enregistrer un commentaire