c++ - template function specialization

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.
 

你可能感兴趣的:(C++)