Templates in C++ programming

Templates allow programmer to create a common class or function that can be used for a variety of data types. The parameters used during its definition is of generic type and can be replaced later by actual parameters. This is known as the concept of generic programming. The main advantage of using a template is the reuse of same algorithm for various data types, hence saving time from writing similar codes.

For example, consider a situation where we have to sort a list of students according to their roll number and their percentage. Since, roll number is of integer type and percentage is of float type, we need to write separate sorting algorithm for this problem. But using template, we can define a generic data type for sorting which can be replaced later by integer and float data type.

Types of templates

Templates in C++ can be divided into major two types, they are

  • Function Template
  • Class Template

As of C++ 11, Variable Template has also been added.

Function Template

A generic function that represents several functions performing same task but on different data types is called function template. For example, a function to add two integer and float numbers requires two functions. One function accept integer types and the other accept float types as parameters even though the functionality is the same. Using a function template, a single function can be used to perform both additions. It avoids unnecessary repetition of code for doing same task on various data types.

Syntax of Function Template

template < class T1, class T2, ... >
returntype function_name (arguments of type T1, T2, ...)
{
    statement(s);
    ... ... ...
}

Example of Function Template

1. C++ program to add two numbers using function template.

#include <iostream>
#include <conio.h>
using namespace std;

template<class t1,class t2>
void sum(t1 a,t2 b) // defining template function
{
    cout<<"Sum="<<a+b<<endl;
}

int main()
{
    int a,b;
    float x,y;
    cout<<"Enter two integer data: ";
    cin>>a>>b;
    cout<<"Enter two float data: ";
    cin>>x>>y;
    sum(a,b); // adding two integer type data
    sum(x,y); // adding two float type data
    sum(a,x); // adding a float and integer type data
    getch();
    return 0;
}

This program illustrates the use of template function in C++. A template function sum() is created which accepts two arguments and add them. The type of argument is not defined until the function is called. This single function is used to add two data of integer type, float type and, integer and float type. We don’t need to write separate functions for different data types. In this way, a single function can be used to process data of various type using function template.

Output

Enter two integer data: 6 10
Enter two float data: 5.8 3.3
Sum=16
Sum=9.1
Sum=11.8

Class Template

Like function template, a class template is a common class that can represent various similar classes operating on data of different types. Once a class template is defined, we can create an object of that class using a specific basic or user-defined data types to replace the generic data types used during class definition.

Syntax of Class Template

template <class T1, class T2, ...>
class classname
{
    attributes;
    methods;
};

Example of Class Template

2. C++ program to use class template

#include <iostream>
#include <conio.h>
using namespace std;

template<class t1,class t2>
class sample
{
    t1 a;
    t2 b;
    public:
        void getdata()
        {
            cout<<"Enter a and b: ";
            cin>>a>>b;
        }
        void display()
        {
            cout<<"Displaying values"<<endl;
            cout<<"a="<<a<<endl;
            cout<<"b="<<b<<endl;
        }
};

int main()
{
    sample<int,int> s1;
    sample<int,char> s2;
    sample<int,float> s3;
    cout <<"Two Integer data"<<endl;
    s1.getdata();
    s1.display();
    cout <<"Integer and Character data"<<endl;
    s2.getdata();
    s2.display();
    cout <<"Integer and Float data"<<endl;
    s3.getdata();
    s3.display();
    getch();
    return 0;
}

In this program, a template class sample is created. It has two data a and b of generic types and two methods: getdata() to give input and display() to display data. Three object s1, s2 and s3 of this class is created. s1 operates on both integer data, s2 operates on one integer and another character data and s3 operates on one integer and another float data. Since, sample is a template class, it supports various data types.

Output

Two Integer data
Enter a and b: 7 11
Displaying values
a=7
b=11
Integer and Character data
Enter a and b: 4 v
Displaying values
a=4
b=v
Integer and Float data
Enter a and b: 14 19.67
Displaying values
a=14
b=19.67

Overloading Template Function

If there are more than one function of same name in a program which differ only by number and/or types of parameter, it is called function overloading. If at least one of these function is a template function, then it is called template function overloading. Template function can be overloaded either by using template functions or normal C++ functions of same name.

Example of Overloading Template Function

3. C++ program to overload template function for sum of numbers.

#include <iostream>
#include <conio.h>
using namespace std;

template<class t1>
void sum(t1 a,t1 b,t1 c)
{
    cout<<"Template function 1: Sum = "<<a+b+c<<endl;
}

template <class t1,class t2>
void sum(t1 a,t1 b,t2 c)
{
    cout<<"Template function 2: Sum = "<<a+b+c<<endl;
}

void sum(int a,int b)
{
    cout<<"Normal function: Sum = "<<a+b<<endl;
}

int main()
{
    int a,b;
    float x,y,z;
    cout<<"Enter two integer data: ";
    cin>>a>>b;
    cout<<"Enter three float data: ";
    cin>>x>>y>>z;
    sum(x,y,z); // calls first template function
    sum(a,b,z); // calls first template function
    sum(a,b); // calls normal function
    getch();
    return 0;
}

In this program, template function is overloaded by using normal function and template function. Three functions named sum() are created. The first function accepts three arguments of same type. The second function accepts three argument, two of same type and one of different and, the third function accepts two arguments of int type. First and second function are template functions while third is normal function. Function call is made from main() function and various arguments are sent. The compiler matches the argument in call statement with arguments in function definition and calls a function when match is found.

Output

Enter two integer data: 5 9
Enter three float data: 2.3 5.6 9.5
Template function 1: Sum = 17.4
Template function 2: Sum = 23.5
Normal function: Sum = 14