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

十年热恋 提交于 2020-01-02 11:05:34

问题


As I know, a rvalue reference cannot be bound to a lvalue. e.g.,

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? e.g.,

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

The compiler won't complain the error. Why?


回答1:


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.



来源:https://stackoverflow.com/questions/49912221/why-a-template-argument-of-a-rvalue-reference-type-can-be-bound-to-a-lvalue-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!