2

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

1 Answer 1

1

types

Let's start from the type

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

Here identity is a wrapper that stores a callable of type lambda(int). You can use std::function too:

std::function<int(int)> identity;

So identity take an int and return an int when you invoke it.

add on the other hand when invoked, takes two ints and returns a callable.

extra () operator

You need to invoke add(1, 2) because the return type of add is a callable, otherwise you cannot do the add(1, 2)() == 3 comparison because of type mismatch.

see the types live on godbolt

Sign up to request clarification or add additional context in comments.

2 Comments

does that mean (in above add function) that return [=] and auto T = [=] { } are actually nested lambdas (lambda within lambda)?
@metablaster add is a lambda that returns another lambda. [=] means capture by value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.