Namespaces
Variants

std::forward_as_tuple

从 zh.cppreference.net
 
 
 
 
定义于头文件 <tuple>
template< class... Types >
std::tuple<Types&&...> forward_as_tuple( Types&&... args ) noexcept;
(C++11 起)
(C++14 起为 constexpr)

构造一个到参数 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';
    // 以下代码存在错误:它会生成包含两个悬空引用的
    // std::tuple<int&&, char&&> 对象
    //
    // auto t = std::forward_as_tuple(20, 'a');
    // m.emplace(std::piecewise_construct, std::forward_as_tuple(10), t);
}

输出:

m[6] = ggggggggg

参见

(C++11)
创建由参数类型定义的 tuple 对象
(函数模板)
(C++11)
创建左值引用组成的 tuple 或将 tuple 解包为独立对象
(函数模板)
(C++11)
通过连接任意数量的 tuple 创建 tuple
(函数模板)
(C++17)
以 tuple 作为参数调用函数
(函数模板)