考虑以下 C++ 代码
template <class... Args>
void f (const int x, const int y, Args&&... args) {
// Do something
}
据我了解,这里的Args
既可以是左值引用也可以是右值引用,这取决于编译时的类型推导。
所以,我应该能够使用 - 调用该函数
float x = 40.0;
f<int, float, double>(10, 20, 30, x, 50.0);
这给了我一个错误,指出它无法将 x 从类型 float
转换为类型 float&&
。
如何使用接受左值和右值引用的可变参数模板定义函数。
最佳答案
As far as I understand,
Args
here could either be lvalue or rvalue references, depending on the type deduction at compile time.
你说对了一半。 Args&&
可以是左值或右值引用。但是 Args
本身要么是左值引用,要么不是引用。一个更简单的案例:
template <typename T> void foo(T&& ) { }
foo(1); // T is int
int x;
foo(x); // T is int&
当您为 x
指定 float
时,您指定该特定参数的类型为 float&&
,并且您不能隐式转换左值float
为右值。您必须强制转换它(通过 std::move
):
f<int, float, double>(10, 20, 30, std::move(x), 50.0);
或者通过float&
指定它是一个左值:
f<int, float&, double>(10, 20, 30, x, 50.0);
或者简单地让演绎发挥作用:
f(10, 20, 30, x, 50.0);
关于c++ - 可变参数模板和 RValue 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034184/