命名空间
变体
操作

std::make_from_tuple

来自 cppreference.cn
< 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)
使用参数元组调用函数
(函数模板) [编辑]