std::tuple_element<std::tuple>

From cppreference.com
< cpp‎ | utility‎ | tuple
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
std::tuple
Member functions
Non-member functions
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Deduction guides(C++17)
Helper classes
tuple_element
 
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 Ith 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

#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
obtains the element types of a tuple-like type
(class template)