Template functions in C++

If you write a function either in C or C++, you should write its parameter types as well as return value type. So if you write int max(int a,int b), the function will operate on two integers.

 What if we have to find maximum of two floats? We have to write another function such as float max(float a,float b). And if we need to use max. of two long values, we write one more function and so on.

This is really wastage of time. We should be able to reuse the code for different type of parameters without explicitly writing another function. That is where template functions are useful.

A template function is the one which can work on different types of values. The type of value, in fact is given as a parameter to the function. And this is called the template parameter.

template <class T>
T find_max(T a, T b)
{
    if (a>b)
      return a;
    return b;
}

Here T is the template parameter. Instead of T we can use any valid label. class is the keyword used for this definition. This word is used because T stands for a class name (or basic data type.)

Instead of class, we can also use typename

 

Template Instantiation


 To use this template function for int and float, we should write code as

int m = find_max<int>(11,-24);
float a,b=1.4,c=2.3;
a = find_max(b,c);

 Here to call find_max function with ints, the template type int is given in angle brackets. 

But it is not necessary to mention the type in angle brackets. Compiler will use the type of the arguments.


Template type can be used inside the function as well.

template <class T>
T find_max(T a, T b)
{
    T max;
    max = a>b?a:b;
    return max;
}
   
What if we need to use more than one generic type? Then we can use multiple template parameters.

template <class T,class M>
M find_square(T a)
{
    M ans ;
    ans = a*a;
    return ans;
}

To call this function, we can use statements such as

unsigned int a;
int b;
a = 45;
b = find_square<int,unsigned int>(a);
  
 
Template specialization

Functions for certain data types should not follow template functions, but should be different.

 e.g. add function should add the two parameters generally. But if the parameters are char pointers, the function should concatenate them. In order to write such functions, we write template with empty angle brackets followed by the function definition. 

template <class T>
T add(T a, T b)
{
    return a+b;
}

template<>
char* add(char* a,char* b)
{
    char *c = strcat(a,b);
    return c;
}

 


int main()
{
   float m=11.2,n=1.5;
   float ans = add<float>(m,n);
   char * a =new char[30];
   strcpy(a,"hello");
   char * b= "world";
   char *c  = add(a,b);
   cout<<"ans is"<<ans<<endl;
   cout<<"c is "<<c<<endl;
   return 0;
}


Here if we call add function with two char pointers then specialized function is called.  

Are there any practical uses of template functions? Of course, the entire STL is Standard Template Library.
 

Comments

Popular Posts