Search code examples
c++rvalue-referencelvaluervalue

Why does && sometimes bind lvalues and other times not?


Ok I have this code:

struct Mine{
    template<typename T>
    Mine(T&& x){
    }
};
void nFoo(int&& x){
}
void sFoo(Mine x){
}

The nFoo takes an int&& directly, while the sFoo does some finagling to get the same effect.

Consider this code:

nFoo(12); //Works

int x = 0;
nFoo(x);  //Cannot bind int (lvalue) to int&&

sFoo(12); //Works
sFoo(x);  //Works

Why does the int&& sometimes allow binding from lvalues and sometimes not?


Solution

  • Why does the int&& sometimes allow binding from lvalues and sometimes not?

    int&& doesn't bind to an lvalue because it is an rvalue reference.

    T&&, in a context where T is a template argument, does bind to an lvalue because it is a forwarding reference. It is not an rvalue reference, even though the syntax is nearly the same.