模板类,通用类型名与非类型参数

来源:互联网 发布:勇士vs活塞数据10.30 编辑:程序博客网 时间:2024/06/05 06:05

C++中有一系列用来存储和修改变量的类,用来实现栈和队列等数据结构,但若是每次遇到一种变量类型就要重写一个存储该类型的stack类未免太麻烦,为了解决这个问题,就需要使用模板类。

例:用模板类实现的一个简单stack类

template <class Type>class Stack{private:       Type items[10];       int top;public:       Stack();       bool push(const Type& item);       bool pop(const Type& item);       bool isfull();};template<class Type>Stack<Type>::Stack(){       top=-1;}template<class Type>bool Stack<Type>::push(const Type& item){       if(top<9){              items[++top]=item;              return true;       }       else{return false;}}template<class Type>bool Stack<Type>::pop(const Type& item){       if(top>0){              item=items[top--];              return true;       }       else{return false;}}template<class Type>bool Stack<Type>::isfull(){       if(top==9)return true;       else return false;}
若要声明一个栈实例,语法如下:
Stack<int> intstack;
Stack<double> doublestack;
Stack<string> stringstack;



模板类还能用于动态定义数组长度,用模板参数来提供常规数组的大小,举例如下:

template<class Type,int n>  //n为一个非类型参数,或称为表达式参数class Stack{private:       Type items[n];       int top;public:       bool isfull;       bool push(const Type& item);       bool pop(const Type& item);};......

若要声明一个栈实例,语法如下:

Stack<int,10> intstack;

Stack<double,20> doublestack;


非类型参数还有一些限制,总结如下:

①非类型参数只能为整型,枚举类型,引用或指针。因此template<class Type,double n>是不合法的,但template<class Type,double *p>是合法的。

②模板代码中不能修改非类型参数的值,也不能使用其地址,所以n++,&n等操作是不合法的。这也造成了模板类创建数组的一大缺点,数组创建后无法动态改变大小。

原创粉丝点击