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
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. 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.