C++ Templates

C++ templates are one of the most powerful features of C++ Programming language. Templates allow programmers to create generic programs. This means that programmer can create a single function or a class to work as a template and then use it in multiple codes with different data sets.

C++ Templates are like algorithms or containers as those are also based on generic programming. For example, the container vector has a single definition but it can be used for different data types as vector<int>, vector<string>.

The real life example of template is search() function, which is used in a large code base. Instead of creating and maintaining different search functions for different types of data, programmer can create a simple search() template. This function template can be used in different modules and for different data types by just changing the data type of search() function. The data type of template can be passed as one of its arguments.

Working of C++ Templates

C++ programming language uses template keyword to define templates. When a template is called in a program, it expands at compile time just like macros. Before expanding, compiler checks the data type of the template and maintains its copy. Hence the compiled code maintains multiple copies of the template function or class.

Types of Templates

Templates are blueprint of a class or function. There can be two types of templates:

  • Function Templates
  • Class Templates

Function Templates

A function template is different from an ordinary function is that same function template can have different data types at once but, the single ordinary function can only have one data type.

The syntax for defining function template is:

Where template is the keyword. The class type is written is angle braces <> after template keyword. The return-type is function return type.

In the code below, TSort() is a generic function, a template. It takes array as input. The array can be of type int, double or float. The TSort() function will work same for each array type.

#include <iostream>
using namespace std;
template <class Temp>
void TSort(Temp t[], int n) {
    for (int i = 0; i < n - 1; i++)
        for (int j = n - 1; i < j; j--)
            if (t[j] < t[j - 1])
              swap(t[j], t[j - 1]);
}
// Driver Program
int main() {
    int t[6] = {15, 50, 16, 44, 20, 11};
    int n = sizeof(t) / sizeof(t[0]);
    cout << "Your array is: ";
    for (int i = 0; i < n; i++)
        cout << t[i] << " ";
    cout << endl;
    TSort<int>(t, 6);
    cout << "The Sorted array is: ";
    for (int i = 0; i < n; i++)
        cout << t[i] << " ";
    cout << endl;   
  return 0;
}

The output of above code after compilation is:

The same function can sort an array having float numbers.

// This code is written by www.tutorialsart.com
#include <iostream>
using namespace std;
template <class Temp>
void TSort(Temp t[], int n) {
    for (int i = 0; i < n - 1; i++)
        for (int j = n - 1; i < j; j--)
            if (t[j] < t[j - 1])
              swap(t[j], t[j - 1]);
}
// Driver Program
int main() {
    float t[6] = {1.5, 5.3, 1.6, 4.4, 2.2, 1.1};
    int n = sizeof(t) / sizeof(t[0]);
    cout << "Your array is: ";
    for (int i = 0; i < n; i++)
        cout << t[i] << ", ";
    cout << endl;
    TSort<float>(t, 6);
    cout << "The Sorted array is: ";
    for (int i = 0; i < n; i++)
        cout << t[i] << ", ";
    cout << endl;   
  return 0;
}

The output of above code after compilation is:

Class Templates

Like Function Templates, programmer can also create class templates for generic class operations. The syntax for defining a class template is:

Where template and class are keywords. The example below shows a template function getmax() that compares two numbers and returns the larger number. Since it is a template function so it can take any data type be it integers or float. In the driver program below, the same getmax() function finds the maximum number between two integers and between two float numbers.

#include <iostream>
using namespace std;
template <class Temp>
class digits {
    Temp x, y;
  public:
    digits (Temp num1, Temp num2)
      {x=num1; y=num2;}
    Temp getmax ();
};
template <class Temp>
Temp digits<Temp>::getmax ()
{
  Temp max;
  max = x>y? x : y;
  cout << "The larger number is: ";
  return max;
}
// Driver Program
int main () {
  digits <int> obj1 (200, 705);
  cout << obj1.getmax();
  cout << endl;
  digits <float> obj2 (0.5, 0.01);
  cout << obj2.getmax();
  return 0;
}

The output of the above code after compilation is:

Advantages of C++ Templates

Following are the advantages of using templates:

  • Templates can be used in large code base as they provide code reusability
  • Templates increase flexibility of the programs
  • Templates are useful to define functions or classes that are independent of data types.
  • Templates are efficient way of code as they reduce the time for writing redundant code.
  • Templates help to keep the code type-safe.
  • Programmer can achieve static polymorphism by using templates as they perform computations on compile time.