Tuple Unrolling
Learn about unrolling tuples by implementing algorithms and accessing elements.
We'll cover the following...
Unrolling the tuple
As tuples cannot be iterated as usual, what we need to do is use metaprogramming to unroll the loop. From the previous section’s example, we want the compiler to generate something like this:
auto t = std::tuple(1, true, std::string{"Jedi"});std::cout << std::get<0>(t) << " ";std::cout << std::get<1>(t) << " ";std::cout << std::get<2>(t) << " ";// Prints "1 1 Jedi"
As we can see, we iterate every index of the tuple
, which means we need the number of types/values contained in the tuple. Then, since the tuple contains different types, we need to write a meta-function that generates a new function for every type in the tuple.
If we start with a function that generates the call for a specific index, it will look like this:
template <size_t Index, typename Tuple, typename Func>void tuple_at(const Tuple& t, Func f) {const auto& v = std::get<Index>(t);std::invoke(f, v);}
We can then combine it with a generic lambda, as you learned in the “Essential C++ Techniques” chapter:
auto t = std::tuple{1, true, std::string{"Jedi"}};auto f = [](const auto& v) { std::cout << v << " "; };tuple_at<0>(t, f);tuple_at<1>(t, f);tuple_at<2>(t, f);// Prints "1 1 Jedi"
With the function tuple_at()
in place, we can then move on to the actual iteration. The first thing we ...