Templates and Collection Classes

OverviewHow Do I

Templates are a good way of implementing collection classes. Version 4.0 and later of the Microsoft Foundation Class Library uses templates to implement six collection classes: , , , , , and . For additional information on using and customizing these classes, see Collections Topics.

The MyStack collection is a simple implementation of a stack. The two template parameters, T and i, specify the type of elements in the stack and the maximum number of that item in the stack. The push and pop member functions add and remove items on the stack, with the stack growing from the bottom.

template <class T, int i> class MyStack
{
    T StackBuffer[i];
    int cItems;
public:
    void MyStack( void ) : cItems( i ) {};
    void push( const T item );
    T pop( void );
};

template <class T, int i> void MyStack< T, i >::push( const T item )
{
    if( cItems > 0 )
     StackBuffer[--cItems] = item;
    else
     throw "Stack overflow error.";
    return;
}

template <class T, int i> T MyStack< T, i >::pop( void )
{
    if( cItems < i )
     return StackBuffer[cItems++]
    else

     throw "Stack underflow error.";
}