C++ Tutorial: Class Templates

We also have the possibility to write class templates, so that a class can have members that use template parameters as types. For example:

 

template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};

 

The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write:

 

mypair<int> myobject (115, 36);

 

this same class would also be used to create an object to store any other type:

 

mypair<double> myfloats (3.0, 2.18);

 

The following example further illustrates the concept of class templates. Here class Stack is a template class so it can be used for various data types like int, float , char etc.
SHARE C++ Tutorial: Class Templates

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share