generic stack template class : template class « Class « C++






generic stack template class

  
#include <iostream>
using namespace std;
const int SIZE = 100;

template <class SType> class stack {
   SType stck[SIZE];
   int tos;
 public:
   stack(void);
   ~stack(void);
   void push(SType i);
   SType pop(void);
 };

template <class SType> stack<SType>::stack()
{
   tos = 0;
   cout << "Stack Initialized." << endl;
}

template <class SType> stack<SType>::~stack()
{
   cout << "Stack Destroyed." << endl;
}

template <class SType> void stack<SType>::push(SType i)
{
   if(tos==SIZE)
    {
      cout << "Stack is full." << endl;
      return;
    }
   stck[tos++] = i;
}
template <class SType> SType stack<SType>::pop(void)
{
   if(tos==0)
    {
      cout << "Stack underflow." << endl;
      return 0;
    }
   return stck[--tos];
}

int main(void)
{
   stack<int> a;
   stack<double> b;
   stack<char> c;
   int i;

   a.push(1);
   a.push(2);
   b.push(99.3);
   b.push(-12.23);

   cout << a.pop() << " ";
   cout << a.pop() << " ";
   cout << b.pop() << " ";
   cout << b.pop() << endl;

   for(i=0; i<10; i++)
      c.push((char) 'A' + i);
   for(i=0; i<10; i++)
      cout << c.pop();
   cout << endl;
}
  
    
  








Related examples in the same category

1.template class with type parameter
2.template class with generic parameter
3.Demonstrate a very simple safe pointer class.
4.A generic safe-array class that prevents array boundary errors.
5.Get storage off stack for array
6.template extending
7.sequence template
8.Template Version of Generic binary sorted Tree.
9.template class with two generic parameters
10.Using exceptions with templates.
11.Passing by reference and using virtual functions in exceptions.
12.Using Non-Type Arguments with Generic Classes
13.Using Default Arguments with Template Classes
14.Generic Classes: demonstrates a generic stack.
15.An Example with Two Generic Data Types
16.Applying Template Classes: A Generic Array Class
17.Explicit Class Specializations for generic template class