Click here to Skip to main content
15,888,337 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
here the template function definition
C++
template<typename T>
void foo(T&& t){}

call of foo
C++
int i = 11;
foo(i);//compile and run!

In the previous code ,are we binding an rvalue reference to a lvalue? why is that possible ?
because we know that if we define foo as :
C++
void foo(int&& t){}

we'll get an error from the call of foo(i).

appreciate for reading.
Posted
Updated 12-Oct-13 4:51am
v5
Comments
Richard MacCutchan 12-Oct-13 9:00am    
Build the program with a bit more code and step through with your debugger and you will find out.
Wang Xin USTC 12-Oct-13 10:09am    
yes,I know from debugging the code that T is deducted as int& ,but I'd like to know what happened behind the scenes : why here we are allowed to bind a rvalue reference to a lvalue?

It compiles because it is a feature in C++. T& is an lvalue reference and T&& is an rvalue reference.

C++
T a;
T& l_ref_to_a = a;  // an lvalue reference
T&& r_ref_to_a = a;  // an rvalue reference


"An rvalue reference to A is created with the syntax A&&. To distinguish it from the existing reference (A&), the existing reference is now termed an lvalue reference. The new rvalue reference behaves just like the existing lvalue reference except where noted...."

Read the rest :
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html[^]
 
Share this answer
 
Comments
Wang Xin USTC 12-Oct-13 10:44am    
well ,thank you.
what I intended to ask is :

void foo(int&& i);
int j = 11;
foo(j); // error because try to bind a rvalue ref to an lvalue.

but when it comes to template function, as in the initial question ,things changed. that is my point.
"If P is an rvalue reference to a cvunqualified
template parameter and the argument is an lvalue, the type “lvalue reference to A” is used in
place of A for type deduction." [ Example:
C++
template <class T> int f(T&&);
template <class T> int g(const T&&);
int i;
int n1 = f(i); // calls f<int&>(int&)
int n2 = f(0); // calls f<int>(int&&)
int n3 = g(i); // error: would call g<int>(const int&&), which
// would bind an rvalue reference to an lvalue

----- ISO (N3690) 14.8.2.1
So,in this question ,T is deducted as int&,so the function is of argument int& && ,which is equivalent of int& (if you take a reference to a reference to a type ,you got a reference to that type)
modified version of codes in the initial question can demonstrate that :
C++
template<typename t="">
void foo(T&& rr){
	rr++;
}
int main(){	
	int i = 11;	
	foo(i);
	cout << i << endl; // output is : 12,because foo modified the local variable
}
</typename>
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900