简体   繁体   English

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

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

As I know, a rvalue reference cannot be bound to a lvalue. 据我所知,右值引用不能绑定到左值。 eg, 例如,

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

compiler complains: error: cannot bind rvalue reference of type 'Foo&&' to lvalue of type 'Foo 编译器抱怨:错误:无法将'Foo &&'类型的右值引用绑定到'Foo类型的左值

But, why a template argument of rvalue reference type can be bound to a lvalue? 但是,为什么可以将右值引用类型的模板参数绑定到左值? eg, 例如,

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

The compiler won't complain the error. 编译器不会抱怨该错误。 Why? 为什么?

You can read this article Universal References in C++11 to understand. 您可以阅读本文的C ++ 11通用参考来理解。 Here some part of it: 这是其中的一部分:

If a variable or parameter is declared to have type T&& for some deduced type T, that variable or parameter is a universal reference. 如果声明某个变量或参数的某个推导类型 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 

Here a relevant for your case excerpt from the Standard : 这与您从标准中摘录的案例有关:

... function template parameter type (call it P) ... If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction. ...函数模板参数类型(称为P)...如果P是转发引用,并且参数是左值,则使用类型“对A的左值引用”代替A进行类型推导。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM