![](/img/trans.png)
[英]Does lvalue-to-rvalue conversion is applied to non-type lvalue template argument?
[英]Why a template argument of a rvalue reference type can be bound to a lvalue type?
据我所知,右值引用不能绑定到左值。 例如,
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进行类型推导。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.