C++ Templates

A template is a blueprint or formula for creating a generic class or a function. In other words, templates are codes written in a way that is independent of any particular type. 

Templates are the foundation of generic programming. The library containers like iterators is examples of generic programming and have been developed using template concept.

Templates can be used to define functions as well as classes.

 

Function template

A normal function can operate on a single data type only.

Eg. If we need to define a function finding greater among two numbers, we can define the function only for a particular data type.

//program showing need for template
#include<iostream>
using namespace std;
int find_max(int a,int b)
{
    int result;
    if(a>b) result= a;
    else result= b;
    return result;
}
float find_max(float a,float b)
{
    float result;
    if(a>b) result= a;
    else result= b;
    return result;
}
char find_max(char a,char b)
{
    char result;
    if(a>b) result= a;
    else result= b;
    return result;
}
int main()
{
    int i1=2, i2=4;
    float f1=3.45 ,f2= 5.55;
    char c1='a',c2='b';
    cout<<"Greater integer: "<<find_max(i1,i2)<<endl;
    cout<<"Greater float: "<<find_max(f1,f2)<<endl;
    cout<<"Greater char: "<<find_max(c1,c2);
}

Through template function, a single general procedure can be applied to a wide variety of data. i.e with template, a single algorithm can be used for different data types.

eg single maximum finding function created which can operate greater finding operation with any type of data.

Format of a template function definition:

template<class template_type,....> 
return_type func_name(parameter_list) { 
      //func body 
}

Example:

Let us use template to define a funtion that finds maximum of two numbers as mentioned above.

//find greater using template
#include<iostream>
using namespace std;
template <class T> T find_max(T a, T b)
{
    T result;
    if(a>b)
        result=a;
    else
        result=b;
    return result;
}
int main()
{
    int i1=2, i2=4;
    float f1=3.45 ,f2= 5.55;
    char c1='a',c2='b';
    cout<<"Greater integer: "<<find_max(i1,i2)<<endl;
    cout<<"Greater float: "<<find_max(f1,f2)<<endl;
    cout<<"Greater char: "<<find_max(c1,c2);
}

The output of the program is:

Greater integer: 4
Greater float: 5.55
Greater char: b
How function template works?

When function template is called, the compiler creates a function that uses the parameter types as the argument passed to the function template.

For example, for function template

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

If we call it with int data, find_max(i1, i2); the compiler generates the find_max() function with int data as

int find_max(int a,int b)
{
    int result;
    if(a>b) result= a;
    else result= b;
    return result;
}

 

Program with more than one template

A function template can be defined with more than templates. 

Syntax:

template <class T1, class T2> return_type func_name(T1 a, T2 b)
{
    //body
}

This makes overloading possible in template function.

Overloading function template
  • We can have multiple function templates with the same name but with different parameter list.
  • Overloaded function template must differ either in terms of number of parameters or their type.
//program that uses more than one template
#include<iostream>
using namespace std;
template <class T> void testfunc(T a)
{
    cout<<"One template: ";
    cout<<a<<endl;
}
template <class T> void testfunc(T a, T b)
{
    cout<<"One template,two arguments: ";
    cout<<a<<" "<<b<<endl;
}
template <class T1, class T2> void testfunc(T1 a, T2 b)
{
    cout<<"Two different templates: ";
    cout<<a<<" "<<b<<endl;
}
int main()
{
    int inum=5;
    float fnum=7.6;
    testfunc(inum);
    testfunc(inum,inum);
    testfunc(inum,fnum);
    testfunc(20,"I'm from Krypton.");
    return 0;
}

The output of the program is:

One Template: 5 
One template, two arguments: 5 5 
Two different templates: 5 7.6 
Two different templates: 20 I'm from Krypton.

The output makes clear that template function with matching argument number and type is being called.

 

Class Template

A class that operate on any type of data is called class template.

General form of declaring class template:

template<class template_type, ….> class class_name { 
      private: 
          //data member of template type or non template type 
          //….. 
      public: 
          //function members with template type argument 
          //and return type. 
};

Syntax for creating a specific instance of class:

class_name<data_type> object;

where, data_type is the data type specified as argument to class template. The data type specified is used by the compiler to replace the template type parameter in the class template definition to create the specific versions of the class.

Example:

Let us define Stack class using template so that it can operate on any types of data.

template <class Type> class Stack
{
private:
    Type st[MAX];
    int top;
public:
    Stack()
    {
        top=-1;
    }
    void push(Type var)
    {
        st[++top]=var;
    }
    //...
};

Now, Stack class is instantiated by defining an object using the template argument.

Eg.

Stack <float> s1;
Stack <int> s2;

This creates an object s1, a stack that stores numbers of type float and object s2, a stack that stores numbers of type int.

Here is complete program.

We could instantiate the class objects of other numerical types with just a single line of code.

C++ Exception Handling