Class Templates In C++

The concept of templates can be extended even to classes. Class templates are usually used for data storage (container) classes. Stacks and linked lists, which we encountered in previous chapters, are examples of container classes.
 
However, the examples of these classes that we presented could store data of type float in a stack we would be required to define a completely new class.
 
It follows that for every new data type that we wish to store , a new stack class would have to be created. Won’t it be nice if we are able to write a single class specification that would work for variables of all types, instead of a single basic type.
 
Enter class templates. Here is a program with class template in action.
 
It is simple process to create a class using a template with anonymous type. The general format is:
 
template <class T>
Class classname
 
{
//……………………
//class member specification
//whenever appropriate
//………………….
};
 
Example :
 
template <class T >
class vector
 
{
T* v;
int size
public :
vector (int m)
{
v = new [size = m];
for ( int i = 0; i < size; i++)
v [i] = 0;
{
vectot(T* a)
{
for(int i = 0; i < size; i++)
v[i] = a[i];
}
T operator* (vector &y)
{
T sum = 0;
for(int i = 0; i < size; i++)
sum += this -> v[i] * y – v[i];
return sum;
}
};
 
Class template with multiple statements
 
We can use more than one generic data type in a class template. They are declared as a comma-separated list within the template specification as shown below:
 
template <class T1, class T2, ………….>
class classname
{
……………………
…………………..(body of class)
……………………
};
 
Example :
 
 
Out put of the program :
 
 
 
Scroll to Top