what is the difference between T& and T&& in template parameter?

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?

1

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

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like