Iterate over tuple elements using std :: apply

I wanted to archive a way to apply a function to each element of a given tuple, and I came up with a solution, which is shown in the following example.

int main()
{
    std::apply([](auto&&... xs)
               { 
                   [](...){}(([](auto&& x){ std::cout << x << "\n"; }(std::forward<decltype(xs)>(xs)), false)...); 
               }, std::make_tuple(1, 2.f, 3.0));
}

This seems to work just fine, except that the tuple elements seem to be processed in an inverted order, which leads to the following output:

3
2
1

Can someone tell me why?

+4
source share
1 answer

The order in which the arguments of your inner, empty lambda are evaluated is [](...){}not specified (even after paper in the evaluation order ).

Just use the comma fold:

std::apply([](auto&&... xs) {
               ((std::cout << std::forward<decltype(xs)>(xs) << '\n'), ...); },
           std::make_tuple(1, 2.f, 3.0));

. - cout . "packize", ( [:]), (std::cout << [:]tup << '\n'), ....

+7

Source: https://habr.com/ru/post/1675343/


All Articles