名前空間
変種
操作

std::tuple_element<std::tuple>

From cppreference.com
< cpp‎ | utility‎ | tuple
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
ヘッダ <tuple> で定義
template< std::size_t I, class... Types >
struct tuple_element< I, std::tuple<Types...> >;
(C++11以降)

タプルの要素の型にコンパイル時にインデックスでアクセスするための機能を提供します。

目次

[編集] メンバ型

定義
type タプルの I 番目の要素の型。ここで I[0sizeof...(Types)) の範囲です。

[編集] 実装例

template<std::size_t I, class T>
struct tuple_element;
 
#ifndef __cpp_pack_indexing
// 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;
};
 
#else
// C++26 implementation using pack indexing
template<std::size_t I, class... Ts>
struct tuple_element<I, std::tuple<Ts...>>
{
    using type = Ts...[I];
};
#endif

[編集]

#include <boost/type_index.hpp>
#include <cstddef>
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
 
template<typename TupleLike, std::size_t I = 0>
void printTypes()
{
    if constexpr (I == 0)
        std::cout << boost::typeindex::type_id_with_cvr<TupleLike>() << '\n';
 
    if constexpr (I < std::tuple_size_v<TupleLike>)
    {
        using SelectedType = 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>();
    }
}
 
struct MyStruct {};
 
using MyTuple = std::tuple<int, long&, const char&, bool&&,
                           std::string, volatile MyStruct>;
 
using MyPair = 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&&>);
 
int main()
{
    printTypes<MyTuple>();
    printTypes<MyPair>();
}

実行結果の例

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&&

[編集] 関連項目

構造化束縛 (C++17) 指定された名前を初期化子のサブオブジェクトまたはタプル要素に束縛します[編集]
タプルライクな型の要素型を取得する
(クラステンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)