3

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?

DarthRubik
  • 3,927
  • 1
  • 18
  • 54
  • 2
    Theres a nice article specifically on this in *Effective Modern C++* by Scott Meyers. – Borgleader Jun 18 '16 at 00:20
  • Possible duplicate of [Why "universal references" have the same syntax as rvalue references?](http://stackoverflow.com/questions/20364297/why-universal-references-have-the-same-syntax-as-rvalue-references) – Borgleader Jun 18 '16 at 00:21

1 Answers1

9

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • is there any source which you can advice to learn lvalue, rvalue, forwarding reference etc. blow-by-blow? – Soner from The Ottoman Empire Jun 18 '16 at 00:29
  • @snr I would imagine that modern C++ text books explain it all in a structured manner. The only C++ book that I own was written pre-c++11, so I don't know any that I can recommend. The document that I've now linked in the answer should describe forwarding references and their relation to the other references quite well. – eerorika Jun 18 '16 at 00:38