Templates in C++
February 3, 2011 Leave a comment
1. Templates enable software reuse by allowing us to define “generic” functions and classes.
2. Suppose you want a function to print an array, where the array may be an int array or a float array or any other type of array that can be printed. One option would be to define separate functions for printing depending on the underlying type of the array elements. The use of templates helps us to avoid having to do that.We could define a generic function (function template) which can be used to print any type of array.
It is done as follows:
template <class T>
void print (T* t_array, const int num)
for (int i = 0; i < num; i ++)
cout << t_array[i] << endl;
Using the template function defined above, we can print an int array or a float array as follows:
print (a, 10); // Assuming that we have already created an integer array called a having size at least 10.
print (b, 10); // Assuming that we have already created a float array called b having size at least 10.
3. Class templates:
Similar to function templates, we can also have generic classes defined using templates.
e.g. suppose that you want to have a Stack of either int or float or char or any other type. We can define a generic class which has elements has elements of type T, where, as we need, we can let T be int or char or anything else.
Here’s how we define a class template:
template <class T>
Stack ( ) ;
int push (const T& element); //pushing element onto Stack
int pop ( T& element); // popping from Stack and copying it into element.
// other possible public members (omitted here).
// private members of the class.
The function prototypes (function declarations) for the constructor, push and pop were given inside the class definition. The function definition, which we’ll give outside the class definition are written, as usual, by referring to the function using the scope resolution operator.
The function push is defined as follows:
int Stack<T> : : push ( const T& element)
// implementation of push.
Note that the name of the class is given as : Stack<T> and not simply Stack.
The constructor is defined as follows:
Stack<T> : : Stack ( )
// implementation of constructor.
Note here that the unqualified name of the constructor is Stack<T> : : Stack, and not Stack<T> : : Stack<T>. This is because once you inside the scope of the class Stack <T>, you can refer to the constructor simply by Stack, and there is no need to refer to it as Stack<T>.
In the main( ) function, we can declare Stacks of int, float etc as follows:
int main ( )
Stack <int> intS;
Stack <float> floatS;
Stack <MyClass> myClassS; // assuming that we have defined a class called MyClass.
/* We can call the class member functions in the usual way. */
floatS.pop(q); // where q is some float variable.