Search code examples
c++templatestuples

Get index of a tuple element's type?


If I have a tuple with different element types like

std::tuple<T0, T1, T2, ...>

And how to get the index of a element type?

template<class T, class Tuple>
struct Index
{
    enum {value = ?;}
};

Thanks.


Solution

  • template <class T, class Tuple>
    struct Index;
    
    template <class T, class... Types>
    struct Index<T, std::tuple<T, Types...>> {
        static const std::size_t value = 0;
    };
    
    template <class T, class U, class... Types>
    struct Index<T, std::tuple<U, Types...>> {
        static const std::size_t value = 1 + Index<T, std::tuple<Types...>>::value;
    };
    

    See it live at Coliru.

    This implementation returns the index of the first occurrence of a given type. Asking for the index of a type that is not in the tuple results in a compile error (and a fairly ugly one at that).