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: CArray, CMap, CList, CTypedPtrArray, CTypedPtrList, and CTypedPtrMap. 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.
// templates_and_collection_classes.cpp
template <class T, int i> class MyStack
{
T StackBuffer[i];
int cItems;
public:
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.";
}
template <class T, int i> T MyStack< T, i >::pop( void )
{
if( cItems < i )
return StackBuffer[cItems++]
else
throw "Stack underflow error.";
}
int main()
{
MyStack<char , 1> v;
v.push('a');
}
template <class T, int i> class MyStack
{
T StackBuffer[i];
int cItems;
public:
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.";
}
template <class T, int i> T MyStack< T, i >::pop( void )
{
if( cItems < i )
return StackBuffer[cItems++]
else
throw "Stack underflow error.";
}
int main()
{
MyStack<char , 1> v;
v.push('a');
}
本文介绍使用模板实现集合类的方法,特别关注微软基础类库中使用的六种集合类,并提供了一个简单的栈类实现示例。
1011

被折叠的 条评论
为什么被折叠?



