C++ template specialization

Introduction

If we want our template to behave differently for a specific type, we provide the so- called template specialization.

In case the argument is of a certain type, we sometimes want a different code.

To do that, we prepend our function or a class with :

template <> 
// the rest of our code 

To specialize our template function for type int, we write:

#include <iostream> 

template <typename T> 
void myfunction(T arg) 
{ 
    std::cout << "The value of an argument is: " << arg << '\n'; 
} 

template <> 
// the rest of our code 
void myfunction(int arg) 
{ 
     std::cout << "This is a specialization int. The value is: " << arg <<  
     '\n'; /*from   w  w w  .  ja va 2 s.  c  o m*/
} 

int main() 
{ 
    myfunction<char>('A'); 
    myfunction<double>(345.678); 
    myfunction<int>(123); // invokes specialization 
} 



PreviousNext

Related