有一个要求,我需要通过可变参数模板将一个右值从1个函数传递给另一个函数。为了避免实际的代码复杂性,下面是使用int的最小示例:

void Third (int&& a)
{}

template<typename... Args>
void Second (Args&&... args) {
  Third(args...);
}

void First (int&& a) {
  Second(std::move(a));  // error: cannot bind ‘int’ lvalue to ‘int&&’
  Third(std::move(a));  // OK
}

int main () {
  First(0);
}
First(0)被正确调用。如果我直接调用Third(int&&),那么使用std::move()可以正常工作。但是调用Second(Args&&...) results in:
error: cannot bind ‘int’ lvalue to ‘int&&’
   Third(args...);        ^
note:   initializing argument 1 of ‘void Third(int&&)’
 void Third (int&& a)

成功完成Second(Args&&...)的正确方法是什么?

仅供引用:在实际代码中,Second(Args&&...)是左值,右值和右值引用的混合。因此,如果我使用:
Third(std::move(args...));

it works。但是,如果有各种争论,那就有问题了。

最佳答案

为了保持右值,您必须moveforward参数

template<typename... intrgs>
void Second (intrgs&&... args) {
  Third(std::forward<intrgs>(args)...);
}

10-08 09:17
查看更多