What is the difference between T& and T&& in template parameter? For example:
template<class T> void f(T& t) {...} template<class T> void f(T&& t) {...} I try the code
template<class T> void f(T&& t) { t = 5; } int main() { int a = 0; f(a); //a == 5 why? return 0; } I expect a = 0 but = 5, why?
11 Answer
In the first case, whatever T is, t is always an lvalue reference:
T = U => T & = U & T = U & => T & = U & T = U && => T & = U & In the second case, t may be an lvalue or rvalue reference. In other words, t is always a reference, but it can bind to any argument. It's a "universal" reference:
T = U => T && = U && T = U & => T && = U & T = U && => T && = U && When you call the second template f(g()), then T is deduced as an lvalue reference if g() is an lvalue, and as a non-reference otherwise.
In your example f(a), since a is an lvalue, T is deduced as int &, so T && = int &, and so the function parameter t is bound to the object a, which you then modify.