Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::tuple_element<std::pair>

      From cppreference.com
      <cpp‎ |utility‎ |pair
       
       
      Utilities library
       
       
      Defined in header<utility>
      template<std::size_t I,class T1,class T2>
      struct tuple_element<I,std::pair<T1, T2>>;
      (since C++11)

      The partial specializations ofstd::tuple_element for pairs provide compile-time access to the types of the pair's elements, using tuple-like syntax. The program is ill-formed ifI >= 2.

      Contents

      [edit]Member types

      Member type Definition
      typeT1 ifI == 0
      T2 ifI == 1

      [edit]Possible implementation

      template<std::size_t I,typename T>struct tuple_element; template<std::size_t I,typename T1,typename T2>struct tuple_element<I,std::pair<T1, T2>>{    static_assert(I<2,"std::pair has only 2 elements!");}; 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;};

      [edit]Example

      Run this code
      #include <iostream>#include <string>#include <tuple> namespace detail{template<std::size_t>struct index_tag{constexprexplicit index_tag()=default;}; template<class T,class U>constexpr T get_val_dispatch(std::pair<T, U>const& pair, index_tag<0>){return pair.first;} template<class T,class U>constexpr U get_val_dispatch(std::pair<T, U>const& pair, index_tag<1>){return pair.second;}}// namespace detail template<std::size_t N,class T,class U>autoconstexpr get_val(std::pair<T, U>const& pair)->typenamestd::tuple_element<N,std::pair<T, U>>::type{return detail::get_val_dispatch(pair, detail::index_tag<N>{});} int main(){auto var=std::make_pair(1,std::string{"one"}); std::cout<< get_val<0>(var)<<" = "<< get_val<1>(var);}

      Output:

      1 = one

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 2974C++11out-of-bounds index referred the undefined primary templatemade ill-formed (hard error)

      [edit]See also

      Structured binding(C++17) binds the specified names to sub-objects or tuple elements of the initializer[edit]
      obtains the type of the specified element
      (class template specialization)[edit]
      obtains the type of the elements ofarray
      (class template specialization)[edit]
      obtains the type of the iterator or the sentinel of astd::ranges::subrange
      (class template specialization)[edit]
      obtains the size of apair
      (class template specialization)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/pair/tuple_element&oldid=154524"

      [8]ページ先頭

      ©2009-2025 Movatter.jp