Template Specialization

Sometimes template classes are not just right for a particular data type. In order to redefine such specialized template classes you need to use template with empty angular brackets followed by class name and type name in angle brackets.

Like this
 template <class T>  
 class Number  
 {  
      T n;  
 public:  
   Number(T n1):n(n1){}  
      T getNumber();  
      void setNumber(T n);  
 };  
 template <class T>  
 T Number<T>::getNumber()  
 {  
      return n;  
 }  
 template<class T>  
 void Number<T>::setNumber(T n1)  
 {  
      n = n1;  
 }  
 template<>  
 class Number<char>  
 {  
      int n;  
      public:  
      Number(char n1);  
      void setNumber(char n1);  
      char getNumber();  
 };  
 Number<char>::Number(char n1)  
      {  
           n = (int)n1;  
      }  
   void Number<char>::setNumber(char n1)        
      {  
           n = (int)n1;  
      }  
   char Number<char>::getNumber()        
      {  
           return (char)n;  
      }  

For the Number template class, specialization is done for char type using

 template<>  
 class Number<char>  
 { 
----------- 
}; 

Do you notice something here? When defining  member functions of specialized template class- Number<char> outside the body of class, template keyword is not used. Instead, just class name with data type in angle brackets is used.

 Number<char>::Number(char n1)  
      {  
           n = (int)n1;  
      }  

When instantiated with int, float etc, generic Number class is used. When instantiated with char, specialized class is used.
         Number<int> nobj(10);//uses generic Number
  cout<<"int number is "<<nobj.getNumber()<<"\n";   
  Number<char> nobjchar('A');//uses Number<char> class
  cout<<"char number is "<<nobjchar.getNumber()<<"\n"; 

Template specialization for function templates

We can write a function with same name as template function. Then this explicit function overrides template function for that data-type. 

In this example, print function is defined explicitly for string type.
template <class T>
void print(T val){
 cout<<"Value is "<<val<<endl;
}
void print(std::string s)
{
 cout<<"String is"<<s;
}
int main(int argc, char **argv)
{
   print(10.2);//uses template function
   string s = "Hello C++ developer";
   print(s);//uses non-template print function
}

It is also possible to overload a template function with another template function.

template <class T>
void print(T val){
 cout<<"Value is "<<val<<endl;
}
template <class T,class U>
void print(T val1,U val2)
{
    cout<<"First value is "<<val1<<"Second value is "<<val2;
}
int main()
{
     int a,b;
     a=b=12;
     float c = 88.8;
     print(a);//first template function
     print(a,c);//second template function
} 
 

Comments

Popular Posts