std::get(std::tuple)

来自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
 
 
在标头 <tuple> 定义
template<std::size_t I, class... Types>

typenamestd::tuple_element<I, std::tuple<Types...>>::type&

    get(std::tuple<Types...>& t )noexcept;
(1) (C++11 起)
(C++14 起为 constexpr)
template<std::size_t I, class... Types>

typenamestd::tuple_element<I, std::tuple<Types...>>::type&&

    get(std::tuple<Types...>&& t )noexcept;
(2) (C++11 起)
(C++14 起为 constexpr)
template<std::size_t I, class... Types>

consttypenamestd::tuple_element<I, std::tuple<Types...>>::type&

    get(conststd::tuple<Types...>& t )noexcept;
(3) (C++11 起)
(C++14 起为 constexpr)
template<std::size_t I, class... Types>

consttypenamestd::tuple_element<I, std::tuple<Types...>>::type&&

    get(conststd::tuple<Types...>&& t )noexcept;
(4) (C++11 起)
(C++14 起为 constexpr)
template<class T, class... Types>
constexpr T& get(std::tuple<Types...>& t )noexcept;
(5) (C++14 起)
template<class T, class... Types>
constexpr T&& get(std::tuple<Types...>&& t )noexcept;
(6) (C++14 起)
template<class T, class... Types>
constexprconst T& get(conststd::tuple<Types...>& t )noexcept;
(7) (C++14 起)
template<class T, class... Types>
constexprconst T&& get(conststd::tuple<Types...>&& t )noexcept;
(8) (C++14 起)
1-4) 从元组提取第 I 个元素。I 必须是 [0sizeof...(Types)) 中的整数值。
5-8) 提取元组 t 中类型是 T 的元素。如果元组不恰好拥有一个该类型元素,那么编译失败。

目录

[编辑]参数

t - 要提取内容的元组

[编辑]返回值

t 的被选中元素的引用。

[编辑]注解

功能特性测试标准功能特性
__cpp_lib_tuples_by_type201304L(C++14)按类型 (5-8) 寻址元组

[编辑]示例

#include <cassert>#include <iostream>#include <string>#include <tuple>   int main(){auto x =std::make_tuple(1, "Foo", 3.14);   // 注意:std::get 会生成到 std::get<std::variant> 的错误链接usingstd::get;   // 基于索引的访问std::cout<<"( "<< get<0>(x)<<", "<< get<1>(x)<<", "<< get<2>(x)<<" )\n";   // 基于类型的访问(C++14 起)std::cout<<"( "<< get<int>(x)<<", "<< get<constchar*>(x)<<", "<< get<double>(x)<<" )\n";   conststd::tuple<int, constint, double, double> y(1, 2, 6.9, 9.6);constint& i1 =std::get<int>(y);// OK:无歧义assert(i1 ==1);constint& i2 =std::get<constint>(y);// OK:无歧义assert(i2 ==2);// const double& d = std::get<double>(y); // 错误:非良构(歧义)   // 注意:std::tie 和结构化绑定也可以用来分解元组为独立对象}

输出:

( 1, Foo, 3.14 ) ( 1, Foo, 3.14 )

[编辑]缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 2485 C++11(按索引)
C++14(按类型)
没有对于 const tuple&& 的重载 添加这些重载

[编辑]参阅

结构化绑定(C++17) 绑定指定的名字到初始化式的子对象或元组元素[编辑]
访问 array 的一个元素
(函数模板)[编辑]
访问 pair 的一个元素
(函数模板)[编辑]
以给定索引或类型(如果类型唯一)读取 variant 的值,错误时抛出异常
(函数模板)[编辑]
std::ranges::subrange 获得迭代器或哨位
(函数模板)[编辑]
std::complex 获取到实部或虚部的引用
(函数模板)[编辑]
close