模板作为参数
模板这种也是可以作为参数的
template <template class Thing>,其中template class 就是带一个泛型的类型,Thing是参数,意味着,Thing接受带一个泛型参数的类型.
利用一个类模板作为作为头文件:
template <typename Type>
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Type items[MAX]; // holds stack items
int top; // index for top stack item
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item); // add item to stack
bool pop(Type & item); // pop top into item
};
template <class Type>
Stack<Type>::Stack()
{
top = 0;
}
template <class Type>
bool Stack<Type>::isempty()
{
return top == 0;
}
template <class Type>
bool Stack<Type>::isfull()
{
return top == MAX;
}
template <class Type>
bool Stack<Type>::push(const Type & item)
{
if (top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
template <class Type>
bool Stack<Type>::pop(Type & item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
一个简单的栈模板类
下面是是一个接受带一个参数的模板的模板类
template <template <typename T> class Thing>
class Crab
{
private:
Thing<int> s1;
Thing<double> s2;
public:
Crab() {}
bool push(int a , double x) {return s1.push(a) && s2.push(x);}
bool pop(int & a , double & x){ return s1.pop(a) && s2.pop(x);}
};
测试函数如下:
int main()
{
Crab<Stack> nebual;
int ni;
double nb;
cout << "Enter int double:\n";
while(cin >> ni >> nb && ni > 0 && nb > 0) // 输入数据<0推退出,或者输入类型不正确推出
{
if(!nebual.push(ni , nb)) // 两个栈有一个满退出
break;
}
while (nebual.pop(ni , nb)) // 都不空打印
cout << ni << ", " << nb << endl;
cout << "Done.\n";
return 0;
}
结果如下: