如何转发打包的可变参数 示例

问题描述

我有一个函数,可以接受打包到元组中的可变参数

template <class... Args>
void Bottom(tuple<Args&&...> t)
{
}

Args&&是转发参考吗?即参考折叠的规则是否适用?或者我只是将&&附加到包中的每个参数上?

说我想从一个肯定会得到转发引用的函数调用函数

template <class... Args>
void Top(Args&&... args) {
  // 1. Bottom<Pack...>();
  // 2. Bottom<Pack&&...>();
}

如果我不想更改参数1或2,哪种语法是最好的?

编辑

我仅使用元组来展示一个打包参数的类。实际的包装类在调用层次结构的不同级别中有所不同。在这种情况下,使用using_fwd_as_tuple的想法很酷,可以找到库的功能

解决方法

我什么也不会说。我将使用std::forward_as_tuple并让编译器进行推导:

template <class... Args>
void Top(Args&&... args) {
  Bottom(std::forward_as_tuple(args...));
}
,

否,tuple<Args&&...> t不是转发参考。它们只能作为顶级参数出现。

您没有添加任何内容,而是试图匹配参数。此类函数仅接受包含r值引用的元组(按值)。

示例

#include <tuple>
using namespace std;

template <class... Args>
void Bottom(tuple<Args&&...> t)
{
}

// Type your code here,or load an example.
int main(){
    double var=0.0;

    tuple<int,double&,char&&> tup1{1,var,'c'};
    //#1
    //Bottom(tup1);

    tuple<int&&,double&&,char&&> tup2{1,0.0,'c'};
    //#2
    //Bottom(tup2);
    //#3
    Bottom(std::move(tup2));
}
  1. 由于参数无法匹配,因此无法编译。
  2. 也不编译。即使参数确实匹配,元组本身也会通过值(在这种情况下是通过副本)传递,并且在存在r值元组成员的情况下删除副本构造函数。
  3. 移动很好,可以实例化以下模板:
    template<>
    void Bottom<int,double,char>(std::tuple<int &&,double &&,char &&> t)
    {
    }