名稱空間
變體
操作

std::make_from_tuple

來自 cppreference.com
< cpp‎ | 工具
 
 
 
定義於標頭檔案 <tuple>
template< class T, class Tuple >
constexpr T make_from_tuple( Tuple&& t );
(C++17 起)
(直至 C++23)
template< class T, tuple-like Tuple >
constexpr T make_from_tuple( Tuple&& t );
(C++23 起)

使用元組 t 的元素作為建構函式的引數,構造型別 T 的物件。

給定僅供闡釋用的函式 /*make-from-tuple-impl*/,定義如下:
template<class T, tuple-like Tuple, std::size_t... I> // C++23 之前對 Tuple 沒有約束
constexpr T /*make-from-tuple-impl*/(Tuple&& t, std::index_sequence<I...>)
{
    return T(std::get<I>(std::forward<Tuple>(t))...);
}

效果等價於
return /*make-from-tuple-impl*/<T>(
    std::forward<Tuple>(t),
    std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{}
);
.

如果

(C++23 起)

則程式非良構。

目錄

[編輯] 引數

t - 其元素用作 T 的建構函式引數的元組

[編輯] 返回值

已構造的 T 物件或引用。

[編輯] 注意

Tuple 不必是 std::tuple,它可以是任何支援 std::getstd::tuple_size 的型別;特別是,可以使用 std::arraystd::pair

(直至 C++23)

Tuple 被約束為類似元組的型別,即其中的每個型別都必須是 std::tuple 的特化,或者建模 tuple-like 的其他型別(例如 std::arraystd::pair)。

(C++23 起)

由於保證複製消除T 不需要是可移動的。

特性測試 標準 特性
__cpp_lib_make_from_tuple 201606L (C++17) std::make_from_tuple

[編輯] 示例

#include <iostream>
#include <tuple>
 
struct Foo
{
    Foo(int first, float second, int third)
    {
        std::cout << first << ", " << second << ", " << third << '\n';
    }
};
 
int main()
{
    auto tuple = std::make_tuple(42, 3.14f, 0);
    std::make_from_tuple<Foo>(std::move(tuple));
}

輸出

42, 3.14, 0

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 3528 C++17 在 1 元組情況下允許包含 reinterpret_cast 等的轉換 已禁止

[編輯] 另請參閱

建立一個由引數型別定義的 tuple 物件
(函式模板) [編輯]
建立一個轉發引用tuple
(函式模板) [編輯]
(C++17)
使用引數元組呼叫函式
(函式模板) [編輯]