C++之forward


不管是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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM