命名空间
变体
操作

std::make_from_tuple

来自 cppreference.cn
< cpp‎ | utility
 
 
 
定义于头文件 <tuple>
template< class T, class Tuple >
constexpr T make_from_tuple( Tuple&& t );
(since C++17)
(until C++23)
template< class T, tuple-like Tuple >
constexpr T make_from_tuple( Tuple&& t );
(since C++23)

构造类型为 T 的对象,使用 tuple t 的元素作为构造函数的参数。

给定仅用于演示的函数 /*make-from-tuple-impl*/ 定义如下
template<class T, tuple-like Tuple, std::size_t... I> // no constraint on Tuple before C++23
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>>>{}
);
.

如果

(since C++23)

则程序是病式的。

目录

[编辑] 参数

t - tuple,其元素将用作 T 构造函数的参数

[编辑] 返回值

构造的 T 对象或引用。

[编辑] 注意

Tuple 不需要是 std::tuple,而可以是任何支持 std::getstd::tuple_size 的东西;特别是,可以使用 std::arraystd::pair

(until C++23)

Tuple 被约束为 tuple-like,即,其中的每种类型都必须是 std::tuple 或另一种类型(例如 std::arraystd::pair),它们模仿 tuple-like

(since C++23)

由于 保证复制省略T 不需要是可移动的。

特性测试 Std 特性
__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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 3528 C++17 在 1-tuple 的情况下,允许包含 reinterpret_cast 等的强制转换 禁止

[编辑] 参见

创建由参数类型定义的 tuple 对象
(函数模板) [编辑]
创建 转发引用tuple
(函数模板) [编辑]
(C++17)
使用 tuple 参数调用函数
(函数模板) [编辑]