为什么右值引用类型的模板参数可以绑定到左值类型?

Why a template argument of a rvalue reference type can be bound to a lvalue type?

本文关键字:绑定 类型 参数 引用类型 为什么      更新时间:2023-10-16

据我所知,右值引用不能绑定到左值。 例如,

void func(Foo &&f) {}
int main() {
Foo f;
func(f);
}

编译器抱怨: 错误: 无法将类型"Foo&&"的右值引用绑定到类型"Foo"的左值

但是,为什么右值引用类型的模板参数可以绑定到左值? 例如,

template <typename T> void funcTemp(T &&arg) {}
int main() {
Foo f;
funcTemp(f);
}

编译器不会抱怨错误。 为什么?

您可以在 C++11 中阅读这篇文章通用参考资料来理解。这里有一部分:

如果某个变量或参数被声明为具有某些推导类型T 的类型T&&的类型,则该变量或参数是通用引用。

Widget&& var1 = someWidget;      // here, “&&” means rvalue reference
auto&& var2 = var1;              // here, “&&” does not mean rvalue reference
template<typename T>
void f(std::vector<T>&& param);  // here, “&&” means rvalue reference
template<typename T>
void f(T&& param);               // here, “&&”does not mean rvalue reference

这里有一个与您的案例相关的标准摘录:

。函数模板参数类型(称为 P)...如果 P 是转发引用,参数是左值,则使用类型"对 A 的左值引用"代替 A 进行类型推断。

相关文章: