头文件Stack_templateValue.h
#ifndef __STACK_TEMPLATEVALUE__
#define __STACK_TEMPLATEVALUE__
#include <deque>
#include <stdexcept>
#include <memory>
template<typename T, template<typename ELEM,
typename /*由于不会用到这个参数所以不写了*/ = std::allocator<ELEM> >
class/*这里只能写class*/ CONT = std::deque>
class Stack {
private:
CONT<T> elems;//保存元素的容器
public:
void push(T const&);//入栈
void pop();//出栈
T top() const;//返回栈顶元素
inline bool empty() const { return elems.empty(); }//返回栈是否为空
template<typename T2, template<typename ELEM2,
typename = std::allocator<ELEM2> >
class CONT2>
Stack<T, CONT>& operator= (Stack<T2, CONT2> const&);
};
#include "Stack_templateValue.cpp"
#endif // !__STACK_TEMPLATEVALUE__
实现头文件Stack_templateValue.h
#ifdef __STACK_TEMPLATEVALUE__
template <typename T, template <typename, typename> class CONT>
inline
void Stack<T, CONT>::push(T const& elem) {
elems.push_back(elem);
}
template <typename T, template <typename, typename> class CONT>
inline
void Stack<T, CONT>::pop() {
if (elems.empty()) {
throw std::out_of_range("Stack<>::pop() : empty stack");
}
elems.pop_back();
}
template <typename T, template <typename, typename> class CONT>
inline
T Stack<T, CONT>::top() const{
if (elems.empty()) {
throw std::out_of_range("Stack<>::top() : empty stack");
}
return elems.back();
}
template <typename T, template <typename, typename> class CONT>
template <typename T2, template <typename, typename> class CONT2>
inline
Stack<T, CONT>& Stack<T, CONT>::operator= (Stack<T2, CONT2> const& op2) {
if ((void*)this == (void*)&op2){
return *this;
}
Stack<T2, CONT2> tmp(op2);
elems.clear();
while (!tmp.empty()) {
elems.push_back(tmp.top());
tmp.pop();
}
}
#endif // __STACK_TEMPLATEVALUE__
测试
#include <iostream>
#include <string>
#include "Stack_templateValue.h"
int main()
{
//模板的模板参数
{
try {
Stack<int> intStack;
Stack<float> floatStack;
intStack.push(42);
intStack.push(7);
floatStack.push(7.7);
floatStack = intStack;
std::cout << floatStack.top() << std::endl;
floatStack.pop();
std::cout << floatStack.top() << std::endl;
}
catch (std::exception const& ex) {
std::cerr << ex.what() << std::endl;
}
}
}