模板型别推导

ParamType是指针或者引用

型别推导规则

  • 若表达式具有引用型别,先将引用部分忽略;
  • 对表达式的型别和param的型别执行模式匹配,来决定T的型别;
param引用无const修饰
template<typename T>
void f(T& param);

int x = 1 ;
const int cx = x ;
const int& rx = x ;

f(x) ; 
f(cx);  
f(rx);
函数调用T的型别param的型别
f(x)intint&
f(cx)const intconst int&
f(rx)const intconst int&
param引用存在const修饰
template<typename T>
void f(const T& param);

int x = 1 ;
const int cx = x ;
const int& rx = x ;

f(x) ; 
f(cx);  
f(rx);
函数调用T的型别param的型别
f(x)intconst int&
f(cx)intconst int&
f(rx)intconst int&
param指针无const修饰
template<typename T>
void f(T* param);

int x = 1 ;
const int* px = &x ;

f(x) ; 
f(px);  
函数调用T的型别param的型别
f(x)intint*
f(px)const intconst int*

param万能引用

template<typename T>
vodi f(T&& param);

int x = 1;
const int cx= x ;
const int& rx = x ;
f(x);
f(cx);
f(rx);
函数调用T的型别param的型别
f(x)int&int&
f(cx)const int&const int&
f(rx)const int&const int&
f(27)int&&int&&

param非引用和指针,按值传递

template<typename T>
void f(T param);
int x = 1;
const int cx= x ;
const int& rx = x ;
const char* const px = "123"; 
f(x);
f(cx);
f(rx);
f(px);
函数调用T的型别param的型别
f(x)intint
f(cx)intint
f(rx)intint
f(27)intint
f(px)const char*const char*

数组实参

  • 数组按值传递将会退化成指针;
  • 如果保持数组的型别,则需要按引用方式传递实参

总结

  • 在模板推导过程中,具有引用型别的实参会被当成非引用型别来处理即其引用性被忽略;
  • 万能引用形参推导时,左值实参会进行特殊处理;
  • 按值传递的推导时,若形参中带有const和valotaile修饰则会被忽略;
  • 数组和函数型别的实参会退化成对应的指针,除非他们被用来初始化引用;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值