std::tuple_element<std::tuple>

来自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
 
 
在标头 <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// 递归情况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...>>{};   // 基础情况template<class Head, class... Tail>struct tuple_element<0, std::tuple<Head, Tail...>>{using type = Head;};   #else// C++26 使用包索引的实现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(){ifconstexpr(I ==0)std::cout<< boost::typeindex::type_id_with_cvr<TupleLike>()<<'\n';   ifconstexpr(I <std::tuple_size_v<TupleLike>){using SelectedType =std::tuple_element_t<I, TupleLike>;   std::cout<<" 位于索引 "<< I <<" 的类型是: "<< boost::typeindex::type_id_with_cvr<SelectedType>()<<'\n'; printTypes<TupleLike, I +1>();}}   struct MyStruct {};   using MyTuple =std::tuple<int, long&, constchar&, 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> 位于索引 0 的类型是: int 位于索引 1 的类型是: long& 位于索引 2 的类型是: char const& 位于索引 3 的类型是: bool&& 位于索引 4 的类型是: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > 位于索引 5 的类型是: MyStruct volatile std::pair<char, bool&&> 位于索引 0 的类型是: char 位于索引 1 的类型是: bool&&

[编辑]参阅

结构化绑定(C++17) 绑定指定的名字到初始化式的子对象或元组元素[编辑]
获得元组式类型的元素类型
(类模板)[编辑]
close