模板笔记4 非类型模板参数
#include <string>
#include <iostream>
#include <stdexcept>
template<typename T, int MAXSIZE>
//template<typename T = int, int MAXSIZE = 100>//可以指定默认值!!!
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(): empty stack");
}
--numElems;
}
template<typename T, int MAXSIZE>
T Stack<T, MAXSIZE>::top () const
{
if (numElems <= 0)
{
throw std::out_of_range("Stack<>::top(): empty stack");
}
return elems[numElems-1];
}
int main()
{
try{
Stack<int,20> int20Stack;
Stack<int,40> int40Stack;
Stack<std::string,40> stringStack;
int20Stack.push(7);
std::cout << int20Stack.top() << std::endl;
int20Stack.pop();
stringStack.push("hello");
std::cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (std::exception const& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
}
非类型模板参数的限制:可以时常整数(包括枚举值)和指向外部链接对象的指针。
不允许是浮点数,类对象和内部链接对象。
错误举例:
template<char const *name>
class Myclass{
...;
};
char const* s = 'hello";//错误不能使用全局指针作为模板参数
Myclass<s> x;//错误,s是指向内部链接对象的指针