In perfect forwarding, std::forward
is used to convert the named rvalue references t1
and t2
to unnamed rvalue references. What is the
A point that hasn't been made crystal clear is that static_cast
handles const T&
properly too.
Program:
#include
using namespace std;
void g(const int&)
{
cout << "const int&\n";
}
void g(int&)
{
cout << "int&\n";
}
void g(int&&)
{
cout << "int&&\n";
}
template
void f(T&& a)
{
g(static_cast(a));
}
int main()
{
cout << "f(1)\n";
f(1);
int a = 2;
cout << "f(a)\n";
f(a);
const int b = 3;
cout << "f(const b)\n";
f(b);
cout << "f(a * b)\n";
f(a * b);
}
Produces:
f(1)
int&&
f(a)
int&
f(const b)
const int&
f(a * b)
int&&
Note that 'f' has to be a template function. If it's just defined as 'void f(int&& a)' this doesn't work.