Search code examples
c++forwarding-reference

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. 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?


Solution

  • 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.