C++: Template Classes

If you need to know how to layout a template class and for what this is used, continue reading this tutorial.


Template class is exactly what it seems, a template. It allows you to define a class and involve variables of unknown type T. Thus, the class can be implemented as a universal class for any group of elements sharing a class or base class.

A stack is a good example which can be used for many types.
CODE Example:

template
class Stack
{
int max;
T** rep; // a dynamic array of pointers to T
int size;
public:
Stack(int); // a constructor
~Stack( ) {delete [ ] rep;} // destructor
bool empty( );
void push(T&);
T& pop( );
};

You could add many more methods to this to expand the explanation, but this shows the use.

NOTE: The method body for the member functions have not been written. These are only the declarations.

This stack is implemented using a dynamic array, which is created by passing the max size to the stack upon creating the object. To create an unending stack, you could implement a Vector or Linked List.

Now, the stack can handle objects of type T which can be any type. If you use primitives, they must all be of the same type in a single stack to prevent chaos in your methods.

If you wish to use only user defined objects, then you could write the methods to call subsequent methods inside your object, based on the current pointer on the stack.
NOTE: This last idea requires that all mixed objects be derived from a single superclass or base class, as the declaration of this stack even as a template requires a given type.

Stack integerStack(20);

Questions/Comments: [email protected]
-William. § (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.