std::tuple_element<std::tuple>
来自 cppreference.com
定义在头文件 <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 // 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) | 将指定的名称绑定到初始化程序的子对象或元组元素 |
(C++11) |
获取类似元组的类型的元素类型 (类模板) |