Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda "call operator" and "parenthesized lambda"

Tags:

c++

syntax

lambda

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.

like image 422
metablaster Avatar asked Sep 18 '26 22:09

metablaster


1 Answers

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

like image 104
Jarod42 Avatar answered Sep 20 '26 11:09

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!