What are Templates?
Templates : - Templates enable us to define generic classes and generic functions. It 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 the actual data type at the time of actual use of that function or class, templates are also sometimes called as parameterized classes or parameterized functions.
- e.g. a class template for an array class would enable us to create arrays of various data types such as int array or float array.
- A template for function swap() would help us create different versions of swap() to swap 2 ints, 2 floats etc.
- Consider swap() function :
template <class T>
void swap (T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
- The call: swap (i, j) would replace the T with datatype of first parameter (ie i in this case).
-
Template for class :template <class T>
class stack
{
T data[max];
int top;
public:
stack()
{
top = -1;
}
void push(T item)
{
// Code to push item on stack
}
T pop()
{
// Code to pop topmost item of the stack
}
};
- Following calls would create stacks of different data types :
stack <int> s1;
stack <char> s2;