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

 

 

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

posted @   imxiangzi  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示