Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd C++ lambda form [duplicate]

Tags:

c++

lambda

In the example in this cppreference page, there is this line of code

[](...){}(n3, n4, x, r2);

What's going on with the "(n3, n4, x, r2)"? Because in this cppreference page, it says all 8 forms of a lambda should end with { body }.

I tried searching online but no luck. Thanks in advance.

like image 474
Gymkata Avatar asked Dec 10 '25 23:12

Gymkata


1 Answers

First, the lambda is:

[](...){}

This is a lambda that captures nothing, has an empty function block, the {}, and uses a C style variadic function parameter to accept any number of parameters.

The whole:

[](...){}(n3, n4, x, r2);

Is what is known as an "immediately invoked lambda expression", as you define the lambda and call it at the same time. The call is the (n3, n4, x, r2), where those 4 variables are passed to the lambda, and nothing happens since the lambda has an empty function block.


To see an actual use case, instead of having to write:

template<typename Tuple, typename Function, std::size_t... Is>
void tuple_for_each_impl(const Tuple& tup, Function func, std::index_sequence<Is...>)
{
    (func(std::get<Is>(tup)), ...);
}

template<typename... Ts, typename Function>
void tuple_for_each(const std::tuple<Ts...>& tup, Function func)
{
    tuple_for_each_impl(tup, func, std::make_index_sequence<sizeof...(Ts)>{});
}

to make a for_each for a tuple, you can instead use:

template<typename... Ts, typename Function>
void tuple_for_each(const std::tuple<Ts...>& tup, Function func)
{
    [&]<std::size_t... Is>(std::index_sequence<Is...>)
    {
        (func(std::get<Is>(tup)), ...);
    }(std::make_index_sequence<sizeof...(Ts)>{});
}
like image 149
NathanOliver Avatar answered Dec 13 '25 15:12

NathanOliver



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!