有一项要求,我需要通过可变参数模板将右值从 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 .但是当参数混合时,它就会出现问题。
最佳答案
你必须使用std::forward
:
template<typename... intrgs>
void Second (intrgs&&... args) {
Third(std::forward<intrgs>(args)...);
}
关于c++ - 通过可变参数模板传递右值引用时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31809416/