Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess Recursion STL Modern C++ Misc Books ----

Templates


Contents

Class Templates

We can also pass a class parameter to a class.


File:: stack1.cpp
#include <iostream>

using namespace std ;

template <class T>
class Stack
{
private:
    int size ;  // number of elements on Stack.
    int top ;
    T* stackPtr ;

public:
    Stack( int initSize = 10 )
           {
              stackPtr = new T[ initSize ]  ;
              top = -1 ;
           }
    ~Stack()
           {
               delete[] stackPtr ;
           }
    void push(const T& value)
           {
               if ( isFull() )
                 {
                   cout << "Stack is full." << endl ;
                    exit(1) ;
                 }
               stackPtr[ ++top ] = value ;
           }
    T pop()
           {
               if ( isEmpty() )
                 {
                    cout << "Stack is Empty." << endl ;
                    exit(1) ;
                  }
                T result ;
                result =  stackPtr[ top ]  ;
                top-- ;
                return result ;
           }
    int isEmpty()const { return top == -1 ; }
    int isFull() const { return top == size - 1 ; }
} ;


int main()
{
   Stack<int> s1 ;
   s1.push( 4 ) ;
   cout << s1.pop() << endl  ;

   Stack<string> s2    ;
   s2.push( "Alan" )    ;
   cout << s2.pop() <<   endl  ;




}

$ g++ stack1.cpp ; ./a.exe
4
Alan

File: container.cpp
#include <iostream>
using namespace std;
/*A conatiner to hold different kinds of objects.*/

template <class T>class container
{
    T* ptr  ;
    int capacity = 10 ;
    int currentSize = 0 ;
    public:
    container ()
    {
        ptr = new T[capacity] ;
    }
    ~container ()
    {
        delete[] ptr ;
    }

    void add( T  obj1 )
    {
        if ( currentSize >= capacity )
         {
             cout << "Reached capacity." << endl ;
             return ;
          }
          ptr[ currentSize++ ] = obj1 ;
    }

    T get( int index )
    {
        if ( index >= currentSize )
        {
            cout << "Invalid index." << endl ;
            throw (  "Invalid index." ) ;
        }
        else
         return ptr[ currentSize-1 ]  ;
    }
};

int main ()
{
    container<int>  object1 ;
    container<string> object2 ;
    object1.add( 10 ) ;
    cout << object1.get(0) << endl ;
    object2.add( "James" ) ;
    cout << object2.get(0) << endl ;
    return 0;
}
The above examples show how we can declare a class template and use it by supplying a type parameter to it.