std:: make_tuple
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Non-member functions | ||||
|
make_tuple
|
||||
|
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(until C++20)
(C++20)
|
||||
| Helper concepts | ||||
|
(C++23)
|
||||
| Helper classes | ||||
|
(C++23)
|
||||
|
(C++23)
|
||||
| Deduction guides (C++17) |
|
定义于头文件
<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
会导致
std::
reference_wrapper
<
X
>
(对于某个类型
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<typename std::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) { return std::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
或将 tuple 解包为独立对象
(函数模板) |
|
(C++11)
|
创建由
转发引用
构成的
tuple
(函数模板) |
|
(C++11)
|
通过连接任意数量的 tuple 来创建
tuple
(函数模板) |
|
(C++17)
|
以 tuple 形式调用函数并传递参数
(函数模板) |