1

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?

Gearoid Murphy
  • 11,834
  • 17
  • 68
  • 86

1 Answers1

2

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);
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • This I understand, what I don't get is how tuples consisting of multiple values are handled using the recursive template method? – Gearoid Murphy Jan 28 '12 at 13:50
  • @GearoidMurphy: You just add variadic template parameters to the tuple definition. You can use `auto`/`decltype` for the return value of `get` to make things simpler. – Kerrek SB Jan 28 '12 at 13:52
  • Aren't variadic templates C++x11?, the boost tuple implementation is not dependent on this feature – Gearoid Murphy Jan 28 '12 at 16:10
  • 1
    @GearoidMurphy: You can "fake" variadic templates up to a finite limit with lots of ugly preprocessor macros. I think that's what Boost does. But conceptually think "variadic". – Kerrek SB Jan 28 '12 at 19:04