函数模版、类模版、类模版和宏

来源:互联网 发布:淘宝妞妞药妆店 编辑:程序博客网 时间:2024/05/16 19:41
一、类模版
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.";}

二、类模版和宏
In many ways, templates work like preprocessor macros, replacing the templated variable with the given type. However, there are many differences between a macro like this:#define min(i, j) (((i) < (j)) ? (i) : (j))and a template:template<class T> T min (T i, T j) { return ((i < j) ? i : j) }Here are some problems with the macro: 宏有以下的几个问题There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.不会进行类型检查;The i and j parameters are evaluated twice. For example, if either parameter has a postincremented variable, the increment is performed two times.当遇到参数中有++、--等时,参数的值会被计算两次;Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging. 宏在预处理时被展开


三、函数模版
template <class T> void MySwap( T& a, T& b ){    T c( a );    a = b; b = c;}
int i, j;char k;MySwap( i, j );     //OK
MySwap( i, k );     //Error, different types.