std::make_tuple

来自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
在标头 <tuple> 定义
template< class... Types >
std::tuple<VTypes...> make_tuple( Types&&... args );
(C++11 起)
(C++14 起为 constexpr)

创建元组对象,从实参类型推导目标类型。

对于 Types... 中的每个 TiVtypes... 中的对应类型 Vistd::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<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++17)
以一个实参的元组来调用函数
(函数模板)