问题描述
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));
}
- 由于参数无法匹配,因此无法编译。
- 也不编译。即使参数确实匹配,元组本身也会通过值(在这种情况下是通过副本)传递,并且在存在r值元组成员的情况下删除副本构造函数。
- 移动很好,可以实例化以下模板:
template<> void Bottom<int,double,char>(std::tuple<int &&,double &&,char &&> t) { }