std::make_tuple
来自cppreference.com
在标头 <tuple> 定义 | ||
template<class... Types> std::tuple<VTypes...> make_tuple( Types&&... args); | (C++11 起) (C++14 起为 constexpr) | |
创建元组对象,从实参类型推导目标类型。
对于 Types...
中的每个 Ti
,Vtypes...
中的对应类型 Vi
为 std::decay<Ti>::type,除非应用 std::decay 对某些类型 X
导致 std::reference_wrapper<X>,该情况下推导的类型为 X&
。
目录 |
[编辑]参数
args | - | 为之构造元组的零或更多实参 |
[编辑]返回值
含给定值的 std::tuple 对象,如同用 std::tuple<VTypes...>(std::forward<Types>(t)...) 创建。
[编辑]可能的实现
template<class T>struct unwrap_refwrapper {using type = T;}; template<class T>struct unwrap_refwrapper<std::reference_wrapper<T>>{using type = T&;}; template<class T>using unwrap_decay_t =typename unwrap_refwrapper<typenamestd::decay<T>::type>::type;// 或使用 std::unwrap_ref_decay_t(C++20 起) template<class... Types>constexpr// C++14 起std::tuple<unwrap_decay_t<Types>...> make_tuple(Types&&... args){returnstd::tuple<unwrap_decay_t<Types>...>(std::forward<Types>(args)...);} |
[编辑]示例
运行此代码
#include <iostream>#include <tuple>#include <functional> std::tuple<int, int> f()// 此函数返回多值{int x =5;return std::make_tuple(x, 7);// C++17 中可以为 return {x,7};} int main(){// 异质元组的构造int n =1;auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n); n =7;std::cout<<"t 的值为 ("<<std::get<0>(t)<<", "<<std::get<1>(t)<<", "<<std::get<2>(t)<<", "<<std::get<3>(t)<<", "<<std::get<4>(t)<<")\n"; // 返回多值的函数int a, b;std::tie(a, b)= f();std::cout<< a <<' '<< b <<'\n';}
输出:
t 的值为 (10, Test, 3.14, 7, 1) 5 7
[编辑]参阅
(C++11) | 创建左值引用的 tuple,或将元组解包为独立对象 (函数模板) |
(C++11) | 创建转发引用的 tuple (函数模板) |
(C++11) | 通过连接任意数量的元组来创建一个tuple (函数模板) |
(C++17) | 以一个实参的元组来调用函数 (函数模板) |