C++泛型编程指南08 函数模板优先级匹配

函数的不同修饰

![[Pasted image 20240810175052.png]]

int max(int a, int  b) {
   
   
    return b < a ? a : b;
}

对于一个普通函数而言,如果对参数和返回类型修饰存在如下形式:

  1. int max(int, int);
  2. int max(const int*, const int*);
  3. int max(int&, int&);
  4. int max(const int, const int);
  5. int max(const int* const, const int* const);
  6. int max(const int&, const int&);
  7. int& max(int&, int&); (确保不返回临时引用,不安全)
  8. int* max(int*, int*); (确保指针非空)
  9. const int* max(const int*, const int*); (确保指针非空)
  10. int& max(const int&, const int&); (确保不返回临时引用,不安全)
  11. int max(const int&&, const int&&); (万能引用)

不要返回临时对象的引用,不要传入和返回空指针

  1. 不要返回临时对象的引用:在某些编程语言中,如C++,临时对象是那些在表达式求值后不再需要的对象,它们通常在表达式结束时被销毁。返回对这些临时对象的引用可能会导致悬挂引用(dangling reference),因为引用的对象可能已经不存在了。
  1. 不要传入和返回空指针:在许多编程语言中,空指针是一个不指向任何有效内存地址的指针。使用空指针可能会导致程序崩溃或未定义行为。因此,避免传递空指针给函数,以及从函数返回空指针是一个不安全的做法。

模板函数的不同修饰

对于一个函数模板而言,对参数和返回值类型进行修饰也是相似的,仅仅是将 特别指定的 类型 int 泛化为一个 模板参数类型 typename T

  1. int max(int, int);
template<typename T>
T max(T a, T b);
  1. int max(const int*, const int*);
template<typename T>
T max(const T* a, const T* b);
  1. int max(int&, int&);
template<typename T>
T max(T& a, T& b);
  1. int max(const int, const int);
template<typename T>
T max(const T a, const T b);
  1. int max(const int* const, const int* const);
template<typename T>
T max(const T* const a, const T* const b);
  1. int max(const int&, const int&);
template<typename T>
T max(const T& a, const T& b);
  1. int& max(int&, int&);
template<typename T>
T& max(T& a, T& b);
  1. int* max(int*, int*);
template<typename T>
T* max(T* a, T* b);
  1. const int* max(const int*, const int*);
template<typename T>
const T* max(const T* a, const T* b);
  1. int& max(const int&, const int&);
template<typename T>
T& max(const T& a, const T& b);
  1. int max(const int&&, const int&&); (万能引用)
template<typename T>
T max(T&& a, T&& b);

修饰带来的功能上的变化

对于在原有函数上面的修饰,会影响他们的功能,比如:

原始版本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丁金金_chihiro_修行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值