# std::tuple_element<std::tuple>

From cppreference.com
< cpp‎ | utility‎ | tuple

Defined in header `<tuple>` |  |
template< std::size_t I, class... Types > struct tuple_element< I, std::tuple<Types...> >; |  | (since C++11)

Provides compile-time indexed access to the types of the elements of the tuple.

### Member types

Member type | Definition
type | the type of `I`th element of the tuple, where `I` is in `[0, sizeof...(Types))`

### Possible implementation

    template< std::size_t I, class T >
    struct tuple_element;

    // recursive case
    template< std::size_t I, class Head, class... Tail >
    struct tuple_element<I, std::tuple<Head, Tail...>>
        : std::tuple_element<I-1, std::tuple<Tail...>> { };

    // base case
    template< class Head, class... Tail >
    struct tuple_element<0, std::tuple<Head, Tail...>> {
       using type = Head;
    };

### Example

Run this code

    #include <iostream>
    #include <string>
    #include <tuple>

    template <typename T> void printHelper() { std::cout << "unknown type\n"; }
    template <> void printHelper<int>() { std::cout << "int\n"; }
    template <> void printHelper<bool>() { std::cout << "bool\n"; }
    template <> void printHelper<char>() { std::cout << "char\n"; }
    template <> void printHelper<std::string>() { std::cout << "std::string\n"; }

    template<std::size_t I, class T>
    void printTypeAtIndex()
    {
        std::cout << "index " << I << " has type: ";
        using SelectedType = std::tuple_element_t<I, T>;
        printHelper<SelectedType>();
    }

    int main()
    {
        struct MyStruct {};
        using MyTuple = std::tuple<int, char, bool, std::string, MyStruct>;
        printTypeAtIndex<0, MyTuple>();
        printTypeAtIndex<1, MyTuple>();
        printTypeAtIndex<2, MyTuple>();
        printTypeAtIndex<3, MyTuple>();
        printTypeAtIndex<4, MyTuple>();
    }

Output:

    index 0 has type: int
    index 1 has type: char
    index 2 has type: bool
    index 3 has type: std::string
    index 4 has type: unknown type

### See also

Structured binding (C++17) | binds the specified names to sub-objects or tuple elements of the initializer
tuple_element (C++11) | obtains the element types of a tuple-like type (class template)

Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/tuple/tuple_element&oldid=140287"