A template is one of the features added to C++ recently. It is a new concept which enables the programmer to define generic classes and functions; thus provides support for generic programming. Generic programming is an approach, where generic types are used as parameters in algorithms so that they work for a variety of suitable data types and data structures.

A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types such as int array and float array. Similarly, we can define a template for a function, say multiply(), that would help us create various versions of multiply() for multiplying int, float and double type values.

A template can be considered as a kind of macro. When an object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function. The templates are sometimes called parameterized classes or functions.

Syntax:

Consider a vector class defined as follows:

Now suppose we want to define a vector that can store an array of float values. We can do this by simply replacing the appropriate int declarations with float in the vector class. This means that we have to redefine the entire class all over again.

Assume that, we want to define a vector class with the data type as a parameter and then use this class to create a vector of any data type instead of defining a new class every time. The template mechanism enables us to achieve this goal:

Template definition of vector class is as shown below:

The class template definition is very similar to an ordinary class definition except the prefix template <class T> and the use of type T. This prefix tells the compiler that we are going to declare a template and use T as a type name in the declaration. Thus, vector has become a parameterized class with the type T as its parameter. T may be substituted by any other data type including the user-defined types. Now, we can create vectors for holding different data types.

A class created from a class template is called a template class. The syntax for defining an object of a template class is as follows:

This process of creating a specific class from a class template is called instantiation. The compiler will perform the error analysis only when an instantiation takes place. It is, therefore, advisable to create and debug an ordinary class before converting it into a template.

Example: Program which illustrates the working of templates.

Output: