The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Templates

Template is a feature which provides support for generic programming. So far, we have defined classes and functions which perform operations on a particular data type. Template allows creation of generic type elements. For e.g, if we define a function which takes int type parameters, the function can operate on integer elements only but using templates, we can define a generic function which can operate on any data type. Similarly, if we define a class called stack with integer type data member, this stack can be used to perform push and pop operations on integer elements only but using templates, we can create a generic stack which can be used for any data type. Templates can be applied to functions and classes.

Function Templates
Function Templates provide a means to make a function generic. In the following program, we implement a swap( ) function which can perform swapping of two elements of any data type.

#include<iostream>
using namespace std;

template <class T>
void swapValues(T &a, T &b) {
   T temp = a;
   a = b;
   b = temp;
}

int main() {
   int a = 5, b = 7;
   float x = 65.39, y = 27.89;
   char p = 'A', q = 'B';

   cout << "Before Swapping :- " << endl;
   cout << "a = " << a << "  b = " << b << endl;
   cout << "x = " << x << "  y = " << y << endl;
   cout << "p = " << p << "  q = " << q << endl;

   /* swap the values stored in variables */
   swapValues(a, b); // swap two integer values
   swapValues(x, y); // swap two float values
   swapValues(p, q); // swap two character values

   cout << "\nAfter Swapping :- " << endl;
   cout << "a = " << a << "  b = " << b << endl;
   cout << "x = " << x << "  y = " << y << endl;
   cout << "p = " << p << "  q = " << q << endl;

   return 0;
}


Class Templates
Consider a class which supports three relational operations ( getMax(), getMin() and isEqual() ). Following program makes the class generic using class template to perform the operations on different data types :

#include<iostream>
using namespace std;

/* Define a generic class to perform relational operation */
template <class T>
class relational {
   T x, y;
public :
   relational(T var1, T var2) {
      x = var1;
      y = var2;
   }
   T getMin() {
      return ((x < y) ? x : y);
   }
   T getMax() {
      return ((x > y) ? x : y);
   }
};

int main() {
   relational<int> r1(11, 17); // object r1 with integer data members
   relational<double> r2(7.1, 6.9); // 'T' is replaced with 'double' type
   int min = r1.getMin(); // get min value of object r1
   double max = r2.getMax(); // get max value of object r2
   cout << "Minimum Element of object r1 : " << min << endl;
   cout << "Maximum Element of object r2 : " << max << endl;
   return 0;
}


Templates with Multiple Parameters
We can also define a template with multiple parameters. See the program below :

#include<iostream>
using namespace std;

// define a template class with two parameters ( T1 and T2 )
template <class T1, class T2>
class X {
   T1 a;
   T2 b;
public :
   X(T1 var1, T2 var2) {
      a = var1;
      b = var2;
   }
   void display() {
      cout << "a : " << a << "  b : " << b << endl;
   }
};

int main() {
   X<int, char> obj1(7, 'M'); // T1 is integer and T2 is character
   X<float, int> obj2(65.71, 8); // T1 is float and T2 is integer
   obj1.display();
   obj2.display();
   return 0;
}


Standard Template Library ( STL )
STL is a C++ library which is built using templates and provide implementation for data structures like stack , queue , array , etc. and algorithms like sort, search, etc. All the implementations are generic i.e they are applicable to any data type. Following program illustrates the use of stack data structure present in STL.
Stack is a last-in-first-out ( LIFO ) type data structure in elements entered last is removed first. It supports only two operations : push( ) which inserts an element into the stack and
                        pop( ) which removes the top element from stack.

#include<iostream>
#include<stack>
using namespace std;

int main() {
   stack<int> s1; // declare a stack object which stores int elements
   s1.push(12); // push an element into stack
   cout << "Element 12 pushed into S1" << endl;
   s1.push(43);
   cout << "Element 43 pushed into S1" << endl;
   cout << "Size of stack s1 : " << s1.size() << endl;
   cout << "Top element of stack s1 : " << s1.top() << endl;
   s1.pop(); // remove the top element
   cout << "Removed the top element from S1" << endl;
   cout << "Now the stack S1 contains " << s1.size() << " element" << endl;
   stack<char> s2;
   s2.push('G');
   cout << "Element 'G' pushed into S2" << endl;
   cout << "Size of stack S2 is " << s2.size() << " and top : " << s2.top();
   s2.push('K');
   cout << "\nElement 'K' pushed into S2" << endl;
   cout << "Now the top element of S2 is " << s2.top() << endl;
   return 0;
}

STL is a very useful library which saves a lot of development time and allows programmer to focus on implementing the logic rather than data structure implementations.

Back