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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」