I just started learning C++17 fold expressions. I understand that it is possible to apply a fold expression to a tuple, like in the following example (inspired by replies to this question):
#include <iostream>
#include <tuple>
int main() {
std::tuple in{1, 2, 3, 4};
std::cout << "in = ";
std::apply([](auto&&... x) { ((std::cout << x << ' '), ...); }, in);
std::cout << std::endl;
std::multiplies<int> op;
auto out = std::apply([&](auto&& ...x) { return std::tuple{op(x, 3)...}; }, in);
std::cout << "out = ";
std::apply([](auto&&... x) { ((std::cout << x << ' '), ...); }, out);
std::cout << std::endl;
}
Output:
in = 1 2 3 4
out = 3 6 9 12
Is it possible to zip two tuples together using a similar approach? Referring to the example above, I would like to replace the constant 3 by another tuple, such as this hypothetical version of std::apply:
auto out = std::apply([&](auto&& ...x, auto&& ...y) { return std::tuple{op(x, y)...}; }, inX, inY);
In case fold expressions are not applicable to this purpose, is there an alternative method to achieve the same result in C++20 (other than template recursion and/oriSFINAE)?
You can apply
twice:
auto out = std::apply([&](auto&&... x){
return std::apply([&](auto&&... y){
return std::make_tuple(op(x, y)...);
}, inY);
}, inX);
Or you can use an index sequence, easier in C++20 since we have more generalized lambda syntax, though still fairly dense:
auto out = [&]<size_t... Is>(std::index_sequence<Is...>){
return std::make_tuple(op(std::get<Is>(inX), std::get<Is>(inY))...);
}(std::make_index_sequence<std::tuple_size_v<decltype(inX)>>());
Might be worth adding a helper like...
auto indices_for = []<typename... Ts>(std::tuple<Ts...> const&){
return = []<size_t... Is>(std::index_sequence<Is...>){
return [](auto f) -> decltype(auto) {
return f(std::integral_constant<size_t, Is>()...);
};
}(std::index_sequence_for<Ts...>());
};
That is, indices_for(t)
gives you a function that takes a function and invokes it with a bunch of integral constants. This is a mess, but it's a mess you have to write one time and can easily test. This lets you write:
auto out = indices_for(inX)([&](auto... Is){
return std::make_tuple(op(std::get<Is>(inX), std::get<Is>(inY))...);
});
Something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With