std::tuple_element<std::pair>

From cppreference.com
< cpplrm; | utilitylrm; | pair
std::pair
Member functions
Non-member functions
(C++11)
Deduction guides(C++17)
Helper classes
(C++11)
tuple_element
(C++11)
Defined in header <utility>
template< class T1, class T2 >
struct tuple_element<0, std::pair<T1,T2> >;
(1) (since C++11)
template< class T1, class T2 >
struct tuple_element<1, std::pair<T1,T2> >;
(2) (since C++11)

The partial specializations of std::tuple_element for pairs provide compile-time access to the types of the pair's elements, using tuple-like syntax.

Member types

First version
Member type Definition
type T1
Second version
Member type Definition
type T2

Possible implementation

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

template<typename T1, typename T2>
  struct tuple_element<0, std::pair<T1,T2> >
  {
     using type = T1;
  };

template<typename T1, typename T2>
  struct tuple_element<1, std::pair<T1,T2> >
  {
     using type = T2;
  };

Example

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

template <int N, typename T, typename U>
static auto constexpr get(std::pair<T, U> const& pair)
    -> typename std::tuple_element<N, decltype(pair)>::type
{
    return N == 0 ? pair.first : pair.second;
}

int main()
{
    auto var = std::make_pair(1, std::string{"one"});

    std::cout << get<0>(var) << " = " << get<1>(var);
}

Output:

1 = one

See also

obtains the type of the specified element
(class template specialization)
obtains the type of the elements of array
(class template specialization)
obtains the size of a pair
(class template specialization)