命名空间
变体
操作

std::make_tuple

来自 cppreference.cn
< cpp‎ | 工具库‎ | tuple
 
 
 
 
定义于头文件 <tuple>
template< class... Types >
std::tuple<VTypes...> make_tuple( Types&&... args );
(C++11 起)
(C++14 起为 constexpr)

创建一个 tuple 对象,从参数类型推导出目标类型。

对于 `Types...` 中的每个 `Ti`,`VTypes...` 中对应的类型 `Vi` 是 std::decay<Ti>::type,除非应用 std::decay 导致 std::reference_wrapper<X> 对于某个类型 `X`,在这种情况下推导出的类型是 `X&`。

目录

[编辑] 参数

args - 用于构造 tuple 的零个或多个参数

[编辑] 返回值

一个 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;
// or use std::unwrap_ref_decay_t (since C++20)
 
template <class... Types>
constexpr // since 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() // this function returns multiple values
{
    int x = 5;
    return std::make_tuple(x, 7); // return {x,7}; in C++17
}
 
int main()
{
    // heterogeneous tuple construction
    int n = 1;
    auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n);
    n = 7;
    std::cout << "The value of t is ("
              << std::get<0>(t) << ", "
              << std::get<1>(t) << ", "
              << std::get<2>(t) << ", "
              << std::get<3>(t) << ", "
              << std::get<4>(t) << ")\n";
 
    // function returning multiple values
    int a, b;
    std::tie(a, b) = f();
    std::cout << a << ' ' << b << '\n';
}

输出

The value of t is (10, Test, 3.14, 7, 1)
5 7

[编辑] 另请参阅

(C++11)
创建左值引用 tuple 或将 tuple 解包为单独的对象
(函数模板) [编辑]
创建一个转发引用tuple
(函数模板) [编辑]
(C++11)
通过连接任意数量的 tuple 创建一个 tuple
(函数模板) [编辑]
(C++17)
使用参数元组调用函数
(函数模板) [编辑]