Traversing nested C++11 tuple



If I have this tuple type:

std::tuple<int, string, std::tuple<...>, int>

How can I traverse it? I’ve been able to write functions that traverse a flat tuple, but not with nested tuples.

The problem seems to be for any implementation of a templated function or type that handles all the conceivable types in a nested tuple, there must be this case:

template<typename T>
void somefunc(T t)
    // Do something to t

Which ends up being the best choice for overload resolution for every type, and you can’t recursively traverse the tuple because you lose the information that it’s a tuple. If you try to write a class or function that tries to determine whether it’s a tuple or not, you still run in to the “false” case which has the same problem as above in that it ends up matching for every type and the tuple specialized version gets overlooked.

Is there a way I’m not aware of to check whether something is a tuple?





Simply overload the someFunc() function for tuples and non-tuple types:

template<typename... Ts>
void someFunc( const std::tuple<Ts...>& tuple )
    /* traverse the elements of the tuple */
    traverse_tuple( tuple );

template<typename T>
void someFunc( const T& value )
    /* do something with the value */

Where traverse_tuple is the same function you have implemented to traverse non-nested (flat) tuples. It calls someFunc() for each member of the tuple.
For an implementation of a tuple traversing function, you could check this answer.


Facebook Comments

Post a comment