The following is a template implementation class for a stack, noting that GCC does not support opening the declaration and definition of a template class (Common class support):
Contents of the TestCC.h file:
#ifndef Testcc_h#defineTestcc_h#include<iostream>#include<vector>#include<stdexcept>Template<typename t>classstack{Private: Std::vector<T>Elems; Public: voidPush (TConst&); voidpop (); T Top ()Const; BOOLEmpty ()Const { returnElems.empty (); }};template<typename t>voidStack<t>::p Ush (TConst&elem) {Elems.push_back (elem);} Template<typename t>voidStack<t>::p op () {if(Elems.empty ()) {ThrowStd::out_of_range ("Stack<>::p op (): Empty Stack"); } elems.pop_back ();} Template<typename t>T Stack<t>::top ()Const{ if(Elems.empty ()) {ThrowStd::out_of_range ("stack<>::top (): Empty Stack"); } returnelems.back ();}#endif //Testcc_h
Test file Main.cpp:
#include <iostream>#include<string>#include<cstdlib>#include"TestCC.h"using namespacestd;intMain () {Try{Stack<int>IntStack; Intstack.push (7); cout<< intstack.top () <<Endl; Stack<string>StringStack; Stringstack.push ("Hello"); cout<< stringstack.top () <<Endl; Stringstack.pop (); Stringstack.pop (); } Catch(std::exceptionConst&ex) {Cerr<<"Exception:"<< ex.what () <<Endl; returnExit_failure;//In stdlib.h }}
Results:
Template class Use Example (i)