Note: function templates do not support template parameters for templates.
Stack defined in Stack7.h:
#ifndef Stack7_h#defineStack7_h#include<deque>#include<stdexcept>#include<memory>Template<TypeName T, template<typename ELEM, TypeName = std::allocator<elem> >classCONT = std::d eque>classstack{ Public: voidPush (TConst&); voidpop (); T Top ()Const; BOOLEmpty ()Const { returnElems.empty (); } template<TypeName T2, template<typename ELEM2, TypeName = std::allocator<elem2> >classCont2>Stack<t, cont>&operator= (Stack<t2, cont2>Const&);Private: CONT<T>Elems;}; Template<typename T, template <typename, typename>classCont>voidStack<t, Cont>::p Ush (TConst&elem) {Elems.push_back (elem);} Template<typename T, template <typename, typename>classCont>voidStack<t, cont>::p op () {if(Elems.empty ())ThrowStd::out_of_range ("Stack<>::p op (): Empty Stack"); Elems.pop_back ();} Template<typename T, template <typename, typename>classCont>T Stack<t, Cont>::top ()Const{ if(Elems.empty ())ThrowStd::out_of_range ("stack<>::top (): Empty Stack"); returnelems.back ();} Template<typename T, template <typename, typename>classCont>Template<typename T2, template <typename, typename>classCont2>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_front (Tmp.top ()); Tmp.pop (); } return* This;}#endif //Stack7_h
Test Code main.cpp:
#include <iostream>#include<string>#include<cstdlib>#include<vector>#include"Stack7.h"using namespacestd;intMain () {Try{Stack<int, std::vector>Vecstack; Vecstack.push (2); Vecstack.push (3); Std::cout<<"Vector Stack ' s top:"<< vecstack.top () <<Std::endl; Vecstack.pop (); Stack<int>IntStack; Stack<float>Floatstack; Intstack.push (6); Intstack.push (7); Floatstack.push (9.9); Floatstack=IntStack; Std::cout<< floatstack.top () <<Std::endl; Floatstack.pop (); Std::cout<<"float Stack ' s top:"<< floatstack.top () <<Std::endl; Floatstack.pop (); Std::cout<<"float Stack ' s top:"<< floatstack.top () <<Std::endl; Floatstack.pop (); } Catch(std::exceptionConst&ex) {Std::cerr<<"Exception:"<< ex.what () <<Std::endl; } return 0;}
Results:
Template parameter usage examples for templates