dimanche 6 octobre 2019

Lambda syntax capturing inside function?

I didn't know how to name the title, hopefully its correct...

I stumbled upon below lambda definition, and don't understand the syntax, wht is the meaning of var = [=] and return [=]?

also second question in ConstexprLambda() function below, why can't we must call add(1, 2) instead of add(1, 2)() why need for additional () while in the call to identity(123) the code makes not use of additional () ?

question(s) is put into comments of the code.

auto identity = [](int n) constexpr
{
    return n;
};

constexpr auto add = [](int x, int y)
{
    auto L = [=] // what is = [=]?
    {
        return x;
    };
    auto R = [=]
    {
        return y;
    };
    return [=] // what return [=] means here?
    {
        return L() + R();
    };
};

void ConstexprLambda()
{
    static_assert(identity(123) == 123);
    static_assert(add(1, 2)() == 3); // why can't we just add(1,2) like above?
}

The example is taken from here

Aucun commentaire:

Enregistrer un commentaire