c++ - 可变参数模板和 RValue 引用

标签 c++ c++11 variadic-templates lvalue rvalue

考虑以下 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/

相关文章:

c++ - 如何在不使用信号槽连接的情况下触发 Action ?

c++ - 如何为单元测试生成文件打开失败

c++ - gcc 要求使用 -std=c++11 即使我已经在使用它

c++ - 模板参数 'F' 不明确

c++ - 为什么 C++11 不能将不可复制的仿函数移动到 std::function?

c++ - 如何返回嵌套在其他包中的模板包?

c++ - 在可变参数模板中使用垫片的更简洁的方法?

c++ - 使用 HWND 切换窗口

c++ - 在类库项目 C++ 中创建模板类

c++ - clang : Fold expression and "expression result unused" warning