Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lvalue binding to rvalue reference

I am trying to understand how lvalues bind to rvalue references. Consider this code:

#include <iostream>

template<typename T>
void f(T&& x) {
    std::cout << x;
}

void g(int&& x) {
    std::cout << x;
}

int main() {
    int x = 4;
    f(x);
    g(x);
    return 0;
}

While the call to f() is fine, the call to g() gives a compile-time error. Does this kind of binding work only for templates? Why? Can we somehow do it without templates?

like image 901
r.v Avatar asked Jun 15 '13 18:06

r.v


1 Answers

Since T is a template argument, T&& becomes a forwarding-reference. Due to reference collapsing rules, f(T& &&) becomes f(T&) for lvalues and f(T &&) becomes f(T&&) for rvalues.

like image 56
David G Avatar answered Sep 30 '22 06:09

David G