std:: tuple_element <std::tuple>
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::tuple
| Member functions | ||||
| Non-member functions | ||||
|
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(C++20)
|
||||
| Helper concepts | ||||
|
(C++23)
|
||||
| Helper classes | ||||
|
tuple_element
<std::tuple>
|
||||
|
(C++23)
|
||||
|
(C++23)
|
||||
| Deduction guides (C++17) |
|
定义于头文件
<tuple>
|
||
|
template
<
std::
size_t
I,
class
...
Types
>
struct tuple_element < I, std:: tuple < Types... > > ; |
(C++11 起) | |
提供对元组元素类型的编译时索引访问。
目录 |
成员类型
| 类型 | 定义 |
| type |
元组中第
I
个元素的类型,其中
I
的取值范围为
[
0
,
sizeof...
(
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() { 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 << " 索引 " << I << " 处的类型为:" << 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> 索引 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) | 将指定名称绑定到初始化器的子对象或元组元素 |
|
(C++11)
|
获取元组类类型的元素类型
(类模板) |