2

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.

metablaster
  • 1,958
  • 12
  • 26
  • 3
    1: As always, `()` after any callable object or function name calls said object or function. – tkausl Aug 21 '21 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. – Swift - Friday Pie Aug 21 '21 at 11:37

1 Answers1

5
  • 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)).

Jarod42
  • 203,559
  • 14
  • 181
  • 302