Programmer's Corner - Using Templates in C++ - Part 2: Class Templates

Backup and Security Solutions 10% off all products with promo code: VISI-P1YR
Get the Programmer's Corner FireFox Search Plug-In

Using Templates in C++


-Sanchit Karve
born2c0de@hotmail.com

 

Now let us assume that we have a Stack class(Data Structure) that is capable of storing only int's. Now suppose you want it to store float's as well. You
would normally write the whole class again by copy/pasting the previous class and make the necessary changes. But hey,There is a much better alternative. Using templates, you can manage just one class that handles different data-types. That way even if you find an error in your class, fixing it will make changes to all the data-types. Here is an example of a templated stack data structure.

#include <dos.h> // For sleep()
#include <iostream.h> // For I/0
#include <windows.h> // FOR MessageBox() API
#include <conio.h>

#define MAX 10 // MAXIMUM STACK CONTENT

template <class T> // Using Templates so that any type of data can be
// stored in Stack without multiple defination of class
class stack
{

  protected:

  T arr[MAX]; // Contains all the Data

  public:
  T item,r;
  int top; //Contains location of Topmost Data pushed onto Stack
  stack() //Constructor
  {
    for(int i=0;i<MAX;i++)
    {
      arr[i]=NULL; //Initialises all Stack Contents to NULL
    }

    top=-1; //Sets the Top Location to -1 indicating an empty stack
  }

  void push(T a) // Push ie. Add Value Function
  {
    top++; // increment to by 1
    if(top<MAX)
    {
      arr[top]=a; //If Stack is Vacant store Value in Array
    }
      else // Bug the User
    {
      MessageBox(0,"STACK IS FULL","STACK WARNING!",MB_ICONSTOP);
      top--;
    }
  }

  T pop() // Delete Item. Returns the deleted item
  {
    if(top==-1)
    {
      MessageBox(0,"STACK IS EMPTY\n","WARNING",MB_ICONSTOP);
      return NULL;
    }
      else
    {
      T data=arr[top]; //Set Topmost Value in data
      arr[top]=NULL; //Set Original Location to NULL
      top--; // Decrement top by 1
      return data; // Return deleted item
    }
  }
};


void main()
{
  stack <int>a; // Create object of class a with int Template
  int opt=1;
  while (opt!=3)
  {
    clrscr();
    cout<<" MAX STACK CAPACITY="<<((MAX-a.top)-1)<<"\n\n\n\n";
    cout<<"1) Push Item\n";
    cout<<"2) Pop Item\n";
    cout<<"3) Exit\n\n";
    cout<<"Option?";
    cin>>opt;
    switch(opt)
    {
      case 1:
        cout<<"Which Number should be pushed?";
        cin>>a.item;
        a.push(a.item);
        break;

      case 2:
        a.r=a.pop();
        cout<<"Item popped from Stack is:"<<a.r<<endl;
        sleep(2);
        break;
    }
  }
}



Everything looks similiar except an object declaration:

  stack <int> s1;


This means that the value T is substituted by int. User-Defined Data Types can also be used provided the required overloaded operator functions are
present.

In case if we define the class functions outside the templated class, the syntax changes a bit. For a Constructor:

  template <class T>
  stack <T>::stack()
  {
    //div
  }



Yes, we have to define that template thing everytime we write a function outside the class.But if a function returns an object of the same
templated class the syntax would be like this:

  stack <T> stack <T>::func(int data)
  {
    //div
  }



Templates can also have pre-defined values like this:

  template <class T,const int max=10>
  class stack
  {
    private:
    T data[max];
    //rest of the members...
  };



Templates can be inherited as well like this:

  class newstack:p ublic stack<T>
  {
    //members...
  };

That's all about templates.  If you use Templates frequently you will save a lot of typing and debugging time.

Suggestions\Questions can be brought to my notice atborn2c0de@hotmail.com

HAVE FUN CODING!!!

Author Information:

Sanchit Karve

http://www.freewebs.com/born2c0de/

born2c0de@hotmail.com

Comments:

Add your comments here.

Name

Comment

You can also send feedback to feedback@programmers-corner.com

There are currently no comments available.