Template class in C++

Template class in C++

A class which is declared such that it can operate on different data types is referred to as a template class.  It is a generic class defined to support various similar operations on different data types.  For example: a class may be created with a data member, such that it can operate upon any type of data member either int, float or char or any other type.  Whenever we require to generalize the definition of a class for various data types used in C++, we may prefer using class templates, as it gives a more general definition for a class.

To declare a template class, we have to use the keyword template followed by class name i.e. template <class nmofclass>, where template and class are keywords and nmofclass is the userdefined name given to a generic class definition.

An example to illustrate the use of template class is given below:

template <class sample>
class abc
{
sample x;
public:
void getx(){cout<<”Enter x?”;cin>>x;}
void putx(){cout<<”x=”<<x;}
};

The data type is specified when the object of the class is created in the manner specified below:

abc <int> obj1;
// class that contains an int variable.
abc <float> obj2;
// class that contains a float variable.

The complete program is as follows:

#include <iostream.h>
#include <conio.h>

template <class sample>

class abc
{
sample x;
public:
void getx()
{
cout<<“\nEnter x?”;
cin>>x;
}
void putx()
{
cout<<“\nx=”<<x;
}
};

void main()
{
clrscr();
abc <int> obj1;
cout<<“\nWorking on integer…!”;
obj1.getx();
obj1.putx();

abc <float> obj2;
cout<<“\n\nWorking on float…!”;
obj2.getx();
obj2.putx();
getch();
}

Thus class templates are required to create generic classes that can refer to any user-defined data type.