命名空间
变体
操作

std::forward_as_tuple

来自 cppreference.cn
< cpp‎ | utility‎ | tuple
 
 
 
 
定义于头文件 <tuple>
template< class... Types >
std::tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept;
(自 C++11 起)
(constexpr 自 C++14 起)

构造一个元组,其元素是对 args 中参数的引用,适合作为参数转发给函数。当使用右值作为参数时,元组具有右值引用数据成员,否则具有左值引用数据成员。

内容

[编辑] 参数

args - 零个或多个用于构造元组的参数

[编辑] 返回值

一个 std::tuple 对象,其创建方式如同 std::tuple<Types&&...>(std::forward<Types>(args)...)

[编辑] 注解

如果参数是临时对象,则 forward_as_tuple 不会延长它们的生命周期;它们必须在完整表达式结束之前使用。

[编辑] 示例

#include <iostream>
#include <map>
#include <string>
#include <tuple>
 
int main()
{
    std::map<int, std::string> m;
 
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple(6),
              std::forward_as_tuple(9, 'g'));
    std::cout << "m[6] = " << m[6] << '\n';
 
    // The following is an error: it produces a
    // std::tuple<int&&, char&&> holding two dangling references.
    //
    // auto t = std::forward_as_tuple(20, 'a');
    // m.emplace(std::piecewise_construct, std::forward_as_tuple(10), t);
}

输出

m[6] = ggggggggg

[编辑] 参见

创建一个由参数类型定义的 tuple 对象
(函数模板) [编辑]
(C++11)
创建一个 tuple 的左值引用,或将一个元组解包为单独的对象
(函数模板) [编辑]
(C++11)
通过连接任意数量的元组来创建一个 tuple
(函数模板) [编辑]
(C++17)
使用元组参数调用函数
(函数模板) [编辑]