Templates:

In C++ programming templates are used to provide more flexibility to the data types. The user can define different data types of variables or return data types using templates in angle brackets (< >).

A keyword template is used in the syntax of templates and a parameter (t) in angled brackets that defines the data type of variables and return data types.

 

Defining a class Template

Let us remind the example of stack that used the concept of undo command. This example is modified using templates that defines different data types. Consider the following example:

# include <iostream>

using namespace std;

# include <conio.h>

Template <class t>

class stack

{

private:

t array [5];

t top;

public:

stack ();

void push  (t d);

t pop ();

};

Template <class t>

stack <t> :: stack ()

{

array [top] =0;

}

Template <class t>

void stack <t > :: push (t d)

{

array [top] =d;

top++;

}

Template <class t>

t stack <t > :: pop ()

{

–top;

return array [top];

}

void main ()

{

stack < int >s;

  1. push (1);
  2. push (2);

stack <float > s1;

s1. push (1.1);

s1. push (2.1);

stack <char > s2;

s2. push (a);

s2. push (b);

cout << s2.pop ();

getche ();

}

Working of the above program:

The above program follows the concept of undo that is first user enters data and then pops out in backward direction. There are three member functions; stack () is the constructor used to initialize the values of data members to zero to avoid garbage values. The function void push (int d) is used to enter the data.

Now take a look on the main () function the line s. push (1) means that the function is called using the object and 1 is passed. 1 is stored in int d. the top of array or array [top] is at zero location, when 1 is passed, the zero location of array has 1 value.

After this the value of top is incremented, it means that now the location of array [top] is 1. Again through main function (2) is passed, and this process is repeated thrice. Now the three locations of arrays have three values 1, 2 and 3 respectively.

After the push function, pop () function is called in the cout statement. The control is transferred to pop () it decrements the value of top and returns the value of array[top] which has the value 3. This value (3) is printed on the screen and the process is continued.

Now we understand the concept of template. Class t is referred to as an instance to the class template and it furthers defines different data types. It is quite clear all the data types are replaced by t, now the user can define which type of data should be passed or returned and the data is printed as instructed.

Note: Template <class t> will always be written before every member function definition.

This concept is called FILO. FILO stands for First in Last out.