不管是T&&、左值引用、右值引用,std::forward都會按照原來的類型完美轉發。
forward主要解決引用函數參數為右值時,傳進來之后有了變量名就變成了左值。
#include <QCoreApplication>
#include <memory>
#include <iostream>
using namespace std;
template <typename T>
void printX(T& lValue)
{
cout << "lValue" << lValue << endl;
}
template <typename T>
void printX(T&& rValue)
{
cout << "rValue" << rValue << endl;
}
template <typename T>
void TestRValue(T && nValue)
{
printX(nValue);
printX(forward<T>(nValue));
printX(move(nValue));
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int nValue = 100;
TestRValue(4);
TestRValue(nValue);
TestRValue(forward<int>(nValue));
return a.exec();
}
lValue4
rValue4
rValue4
lValue100
lValue100
rValue100
lValue100
rValue100
rValue100