c++ - template function specialization

本文详细探讨了C++中模板函数特化的概念及其应用。通过一个具体的最大值函数模板示例,介绍了如何针对特定类型进行特化处理,并讨论了特化可见性和命名空间规则等关键点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this post, we are going to discuss the template function specialiation ;

so what is "template function specialiation"?

 

 given an example, for the following function template

  template <class T>
     T max (T t1, T t2) 
	 {
	    return (t1 > t2 ? t1 : t2);
     }
it works for most value types, however what if the type passed in is a pointer, list const char *, or what if the function does not provide the less than operator and it provides some alternatives;

 

In such situation we might provide a specified template with a more explicity value of parameter type and define/declare the template's body for that specialized type parameter.

 

to declare the specialization of max for template argument of const char * (typedefed as PCC), you can do this :

 

// the below is the template specialization on the type argument of const char * (typedefed as PCC)
typedef const char * PCC;

using std::strcmp;


template<>
PCC max<PCC>(PCC t1, PCC t2)
{
	return (strcmp(t1, t2) > 0 ? t1 : t2);
}

 

there is on tip, if the template argument can be deduced, we can omit the <T> part after the function's name in the function's explicit specializationm, use this:

 

 

// it is possible to omit the template argument if the type of 
// template argument can be deduced from the the function parameters
template<>
PCC max(PCC t1, PCC t2) 
{
	return (strcmp(t1, t2) >0 ? t1 : t2);
}
 

there are some pith/gist/quintessence/essence points that you may want to know about the function template expclit specialization.

 

1. specialiation visiblity rule

 

if you provide a function template specialiation, it should be visible in every file that uses it. otherwise, there would be compilation error (you can not hvae some instantiation for the same template argument from the generic template function, and some instantiation from the specializatoin)

 

normally, you should put the specialization in the header file with the generic template.

 

2. namespace rule

 

Second, the function template specialiation should be in the same namespace as the template that it specialize

 

below shows an error that can be generated through the code below. 

 

// primer.h
namespace cplusplus_primer {
  template <class type>
    type min(Type* array, int size) { /* ... * / }

}

// user.h
class SmallInt { /*   * / } 

// user.C
template< > SmallInt min(SmallInt * array, int size); // this is an error, because it is a differente namespace from the generic template.
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值