jmegaffin
jmegaffin

Reputation: 1172

Type indexed tuple

How can you implement a tuple class that accesses elements by type rather than by index? Something along the lines of this interface...

template<typename... T>
class Tuple
{
public:
    Tuple(T... elements);

    template<typename U>
    U &get();               // U is one of the types in T...
};

Upvotes: 3

Views: 231

Answers (1)

yngccc
yngccc

Reputation: 5684

The way you implement Tuple with variadic template is something like this

// Base case, Tuple<>
template< typename... Ts >
class Tuple {
};

// recursive inheritance :D
template< typename T, typename... Ts >
class Tuple< T, Ts... > : private Tuple< Ts... > {
public:
   // we implement get() by checking wether element type match with
   // request type
   template< typename t >
   typename std::enable_if< std::is_same< t, T >::value, t& >::type
   get() {
     return element;
   }

   // above is not enough since it only check this class's element type,
   // we can check the rest of the tuple by inspecting its the parent classes.
   template< typename t >
   typename std::enable_if< !( std::is_same< t, T >::value ), t& >::type
   get() {
       return Tuple<Ts...>::template get<t>();  // call its parent's get() 
                                                // ::template to shut compiler up
   }       

private:
    T element;
};


Tuple< short, int, float, double, char, std::string > t;
auto x = t.get< std::string >();    //  x will be an empty string.

This assume no duplicate element type, if there is it will pick the one on the front most. If request type is not in Tuple, it won't compile.

Upvotes: 2

Related Questions