How does the boost tuple 'get' method work?

830 views Asked by At

After delving into the source of the excellent boost tuple class (tuple_basic.hpp), I can see that a recursive templated algorithm is used in the 'get' method for accessing the tuple members.

What I'm struggling to understand is how a numeric templated parameter can be mapped into a specific member name?, additionally, won't the recursive template function always converge to the first element (as in, the stop condition of the recursive template function, get<0>())?, how are elements greater than zero accessed?

1

There are 1 answers

4
Kerrek SB On

As a baby example, you can imagine something like this - just a tuple of one fixed type for now:

template <int N> struct MyTuple : MyTuple<N - 1>
{
    T data;
};
template <> struct MyTuple<0> { };

The real-world solution would of course have variadic template parameters for the data types, and would also provide a variadic constructor, constructing data with the first element and passing the remaining elements to the base constructor.

Now we can try and access the ith element:

template <int K> struct get_impl
{
    template <int N> static T & get(MyTuple<N> & t)
    {
        return get_impl<K - 1>::get(static_cast<MyTuple<N - 1>&>(t));
    }
};
template <> struct get_impl<0>
{
    template <int N> static T & get(MyTuple<N> & t)
    {
        return t.data;
    }
};

The key here is to have a specialization when K = 0 which extracts the actual element, and to cast up the inheritance hierarchy until you're there. Finally, we slingshot the tuple type deduction through a function template:

template <int K, int N> T & get(MyTuple<N> & t)
{
    return get_impl<K>::get(t);
}