From cppreference.com
template<std::size_tI,class...Types>structtuple_element<I,std::tuple<Types...>>;(since C++11)Provides compile-time indexed access to the types of the elements of the tuple.
Member types
Type Description typethe type of Ith element of the tuple, where I is in [0, sizeof...(Types))Possible implementation
template<std::size_tI,classT>structtuple_element;#ifndef __cpp_pack_indexing// recursive casetemplate<std::size_tI,classHead,class...Tail>structtuple_element<I,std::tuple<Head,Tail...>>:std::tuple_element<I-1,std::tuple<Tail...>>{};// base casetemplate<classHead,class...Tail>structtuple_element<0,std::tuple<Head,Tail...>>{usingtype=Head;};#else// C++26 implementation using pack indexingtemplate<std::size_tI,class...Ts>structtuple_element<I,std::tuple<Ts...>>{usingtype=Ts...[I];};#endifExample
Run this code
#include<boost/type_index.hpp>#include<cstddef>#include<iostream>#include<string>#include<tuple>#include<utility>template<typenameTupleLike,std::size_tI=0>voidprintTypes(){ifconstexpr(I==0)std::cout<<boost::typeindex::type_id_with_cvr<TupleLike>()<<'\n';ifconstexpr(I<std::tuple_size_v<TupleLike>){usingSelectedType=std::tuple_element_t<I,TupleLike>;std::cout<<" The type at index "<<I<<" is: "<<boost::typeindex::type_id_with_cvr<SelectedType>()<<'\n';printTypes<TupleLike,I+1>();}}structMyStruct{};usingMyTuple=std::tuple<int,long&,constchar&,bool&&,std::string,volatileMyStruct>;usingMyPair=std::pair<char,bool&&>;static_assert(std::is_same_v<std::tuple_element_t<0,MyPair>,char>);static_assert(std::is_same_v<std::tuple_element_t<1,MyPair>,bool&&>);intmain(){printTypes<MyTuple>();printTypes<MyPair>();}Possible output:
std::tuple<int, long&, char const&, bool&&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, MyStruct volatile> The type at index 0 is: int The type at index 1 is: long& The type at index 2 is: char const& The type at index 3 is: bool&& The type at index 4 is: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > The type at index 5 is: MyStruct volatile std::pair<char, bool&&> The type at index 0 is: char The type at index 1 is: bool&& See also
(C++17)binds the specified names to sub-objects or tuple elements of the initializer
(C++11)
obtains the element types of a
type
(class template)
(C++26)
obtains a reflection of element types of the
type
(function)
(C++11)
obtains the type of the elements of pair
(class template specialization)
std::tuple_element<std::array>
(C++11)
obtains the type of the elements of array
(class template specialization)
std::tuple_element<std::ranges::subrange>
(C++20)
obtains the type of the iterator or the sentinel of a
(class template specialization)
std::tuple_element<std::complex>
(C++26)
obtains the underlying real and imaginary number type of a
(class template specialization)
(C++11)
obtains the size of a tuple
(class template specialization)
(C++11)
tuple accesses specified element
(function template)