A fairly common task one encounters is iterating over a std::tuple.
I’m going to keep this post fairly brief and go over how not to iterate
over a tuple. We’ll discuss how you should iterate over a tuple in the
The most naive way to iterate over a tuple is via recursive function calls
using SFINAE to end the recursion. Here is one way to implement a transform
over a tuple with recursion:
If you prefer, you can write the code such that the function counts up instead of
down, but aside from that this is pretty much what we’re stuck with in C++11/14.
In C++17, constexpr-if can be used so that we only have one function, but
nevertheless we are doing recursion.
With the above could you can do both a
fold, and a
(referred to as map in functional languages). Here is an example of using
a fold to compute the sum of elements in a tuple (yes, yes, in this case a
std::vector would work fine, humor me for the purposes of this example).
A transform can be performed similarly but the compile time integral
value must be extracted from index using decltype(index)::value. The
compile time index can then be used to index a second tuple as follows:
The lines of interest are 5 and 6. On 5 we assign the value held in the
std::integral_constant to a constexpr variable, and on line 6 we use the
constexpr variable to retrieve an element from the tuple.
As I mentioned at the beginning, this post is fairly short and I don’t go into
much detail because this is the way you shouldn’t iterate over a tuple. I’m
posting the correct way to iterate over a tuple at the same time
here so you can compare them both.