C++之forward

发布时间 2023-04-30 11:52:41作者: imxiangzi

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

 

 

https://www.cnblogs.com/xzlq/p/15256974.html