c++tricks——模板函数重载

本文详细介绍了VS2015 C++编译器中模板特化的规则,包括不同类型参数如T、T* 和 const T* 的特化顺序,并通过示例程序演示了这些规则的应用。

vs2015 c++编译器规则:

  • A template specialization for a specific type is more specialized than one taking a generic type argument.
  • A template taking only T* is more specialized than one taking only T, because a hypothetical type X* is a valid argument for a T template argument, but X is not a valid argument for a T* template argument.(T*与T区别)
  • const T is more specialized than T, because const X is a valid argument for a T template argument, but X is not a valid argument for a const T template argument.(const T与T区别)
  • const T* is more specialized than T*, because const X* is a valid argument for a T* template argument, but X* is not a valid argument for a const T* template argument.(const T*与T*区别)

// partial_ordering_of_function_templates.cpp  

// compile with: /EHsc  

#include <iostream>  

  

extern "C" int printf(const char*,...);  

template <class T> void f(T) {  

   printf_s("Less specialized function called\n");  

}  

template <class T> void f(T*) {  

   printf_s("More specialized function called\n");  

}  

template <class T> void f(const T*) {  

   printf_s("Even more specialized function for const T*\n");  

}  

  

int main() {  

   int i =0;  

   const int j = 0;  

   int *pi = &i;  

   const int *cpi = &j;  

  

   f(i);   // Calls less specialized function.  

   f(pi);  // Calls more specialized function.  

   f(cpi); // Calls even more specialized function.  

   // Without partial ordering, these calls would be ambiguous.  

}  

/** output

Less specialized function called  

More specialized function called  

Even more specialized function for const T*  

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值