std::make_tuple

出自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
 
 
在標頭 <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)
以一個實參的元組來調用函數
(函數模板) [編輯]