Templates

Template Functions

//Parametrized swap
template < class Type >
void swap(Type& a, Type& b)
{
     Type temp = a;
     a = b;
     b = temp;
}

//Parametrized min
template < class Type >
Type min(Type a, Type b)
{
     return a < b ? a : b;
}

//Parametrized max
template < class Type >
Type max(Type a, Type b)
{
     return a > b ? a : b;
}

//Overloading of min for array
template < class Type >
Type min(const Type* array, int size)
{
     Type m = array[0];
     for( int i = 1; i < size; ++i )
          if (array[i] < m)
               m = array[i];
     return m;
}

Array Template

template < class T >
class Array
{
     public:
          //default constructor
          explicit Array(int s = 10): size_(s), data_(new T[size_])
                { assert(s != 0); }
          //conversion constructor
          Array(T* d, int s): size_(s), data_(d) {};
          //destructor
          ~Array() { delete [] data_; }
          //accessors
          void showAll();
          void showEnds();
     private:
          T*  data_;
          int size_;
};

template < class T >
void Array::showAll()
{
     for( int i=0; i< size_; ++i)
          cout << data_[i] << endl;
     cout << "-----------------------" << endl;
}

template < class T >
void Array::showEnds()
{
     cout << "First element: " << data_[0] << endl;
     cout << "Last  element: " << data_[size_-1] << endl;
     cout << "-----------------------" << endl;     
}

Stack Template

template < class TYPE >
class Stack {
public:
   //default constructor
   explicit Stack(int size = 100)
      : capacity_(size), top_(EMPTY), data_(new TYPE[size])
      { assert(size != 0); }
   //destructor
   ~Stack() { delete [] data_; }
   //accessors
   TYPE  top_of()const { return data_[top]; }
   bool  empty()const { return top_ == EMPTY;}
   bool  full()const { return top_ == capacity_ - 1;}
   //mutators
   void  push(TYPE c) { data_[++top_] = c; }
   TYPE  pop() { return data_[top_--]; }
   void  reset() { top_ = EMPTY; }

private:
   enum   { EMPTY = -1 };
   TYPE*  data_;
   int    capacity_;
   int    top_;
};