What makes rvalue reference able to do Perfect Forwarding?


(C++11, Visual Studio 2010)
R-value reference itself cannot do Perfect Forwarding. It needs three more things:
1 template function: it’s impossible to do perfect forwarding for non-template functions,
because rvalue reference parameter doesn’t bind to lvalue argument.
2 special rule made for && in template argument deduction, which is T&&& collapsing to T&.
3 cast(std::forward) is needed because in ‘Rref0(T&& t)’ t has a name and named T&& is treated as T& if no casting.
The following code demonstrates perfect forwarding:

void Rref2(const int& i)
{
	cout << "Rref2(const int& i)" << endl;
};
void Rref2(int& i)
{
	cout << "Rref2(int& i)" << endl;
};
template <class T> void Rref0(T&& t)
{
	Rref2(std::forward<T>(t));
}
void TestRref()
{
	int i = 4;
	const int ci = 5;
	Rref0(i);
	Rref0(ci);
	Rref0(6);
}
Advertisements
Comments are closed.
%d bloggers like this: