3

I've read an answer and stumbled upon sample code below which is Elliott's answer from other SO question HERE

I have issue trying to understand two things (and to know how this syntax is called) :

#include <iostream>

template <typename ... T>
void Foo (T && ... multi_inputs)
{
    int i = 0;
    
    ([&] (auto & input)
    {
        // Do things in your "loop" lambda
    
        ++i;
        std::cout << "input " << i << " = " << input << std::endl;

    } (multi_inputs), ...);
}


int main()
{
    Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
    
    return 0;
}

Two questions each with subquestion:

  1. At the end of lambda is expression (multi_inputs), ...

This is equivalent to following simplified syntax:

auto y = [&]() { }();

I don't understand 2 things here, what is the final () called, and what it does? I assume this is some kind of function call operator, but it looks like redundant if taken out of context.

  1. The entry lambda itself is enclosed into parentheses ()

This is equivalent to following simplified syntax:

(auto y = [&]() { }());

Here I want to understand same, what is this syntax called and what it does in and out of this context? I assume this is also some sort of "parentheses operator" but don't know anything about it.

Knowing what these parentheses do is one thing, but also knowing what is this syntax called is important for understanding ex. to know what to look up on cppreference.

2
  • 3
    1: As always, () after any callable object or function name calls said object or function. Commented Aug 21, 2021 at 11:27
  • 2
    note , lambda here got a templated call operator defined, a call of lambda within fold expression calls an instance of such for every component of argument pack. There is no redundancy here. Commented Aug 21, 2021 at 11:37

1 Answer 1

7
  • f is a lambda here

    auto f = []() { return 42; };
    int i = f(); // i = 42
    

    whereas, adding () immediately call the lambda:

    int i = []() { return 42; }(); // lambda called immediately
                                   // i = 42;
    
  • (f<Ts>(), ...) or (f(args), ...) are fold expressions (with comma operator) to expands variadic template.

    they are equivalent to

    (f<T0>(), f<T1>(), .., f<Tn>()) or (f(arg0), f(arg1), .., f(argN)).

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

1 Comment

Clear explanation and to the point, thanks!

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.