非类型的函数模板参数
#include <stdexcept>
template <typename T,int MAXSIZE>
class Stack
{
private:
T elems[MAXSIZE];
int numElems;
public:
Stack();
void push(T const&);
void pop();
T top() const;
bool empty() const{return numElems==0;}
bool full() const {return numElems==MAXSIZE;}
};
//构造函数
template <typename T,int MAXSIZE>
Stack<T,MAXSIZE>::Stack():numElems(0)
{
}
template <typename T,int MAXSIZE>
void Stack<T,MAXSIZE>::push(T const& elem)
{
if (numElems==MAXSIZE)
{
throw std::out_of_range("Stack<>::push(): Stack is full");
}
elems[numElems]=elem;
++numElems;
}
template <typename T,int MAXSIZE>
void Stack<T,MAXSIZE>::pop()
{
if (numElems==0)
{
throw std::out_of_range("Stack<>::pop(): Stack is empty");
}
--numElems;
}
template <typename T,int MAXSIZE>
T Stack<T,MAXSIZE>::top() const
{
if (numElems<=0)
{
throw std::out_of_range("Stack<>::pop(): Stack is empty");
}
return elems[numElems-1];
}
#include <iostream>
#include <string>
#include <cstdlib>
#include "1.h"
int main()
{
try
{
Stack<int,20> int20Stack; //可以存储20个int元素的栈
Stack<int,40> int40Stack; //可以存储40个int元素的栈
Stack<std::string,40> stringStack; //可以存储40个string元素的栈
//使用可存储20个int元素的栈
int20Stack.push(7);
std::cout<<int20Stack.top<<std::endl;
int20Stack.pop();
//使用可存储40个string元素的栈
stringStack.push("123321");
std::cout<<stringStack.top()<<std::endl;
stringStack.pop();
stringStack.pop();
}
catch(std::exception const& ex)
{
std::cerr<<"Exception: "<<ex.what()<<std::endl;
return 1;
}
return 0;
}
非类型模板参数是有限制的,他们可以是常整数(包括枚举值)或者指向外部链接对象的指针, 但是浮点数,类对象和内部链接对象(string)是不允许作为非类型模板参数的