Free Webmasters Resources, Webmaster Tools, CGI Scripts, Web Tutorials, Web Articles
  Advertise  •  Webmaster Resources  •  Webmaster Forums  •  Webmaster Tools  •  Webmaster Articles  •  Tutorials






Templates in C++

Home Page :: Authors Login :: Author Signup :: More Articles

Home :: Other Languages


About This Author :: Request Reprint :: Print Article :: Tell A Friend


Templates in C++
By Sanchit Karve

INTRODUCTION

Before I start this tutorial I assume that you have a Working Knowledge of OOP in C++. Without this, the tutorial will be of no use to you.

This tutorial shows you how to Reuse Code, Save Typing Time, Prevent Time Spent on Debugging and saving source-code space.

OK. Let me take a common example. The gr8 min() function returns the value which is lowest from the given two arguments.I shall show two xamples now. One without Templates and one with Templates.Here is the first program.


#include <iostream.h>

int min(int a,int b)
{
  return (a < b)?a:b;
}

float min(float a,float b)
{
  return (a < b)?a:b;
}

char min(char a,char b)
{
  return (a < b)?a:b;
}


void main()
{
int a=10,b=5;
cout<<min(a,b)<<'\n';
char p='A',q='Z';
cout<<min(p,q)<<'\n';
float z=1.91,x=3.98;
cout<<min(z,x)<<'\n';
}



OUTPUT:

5
A
1.91

Function Overloading doesn't help much as far as typing time and source space is concerned.Also if you find an error in one such function,you have to correct it in all the other functions as well.With Templates all the work becomes a lot easier. Let's see the Templated Version now...


#include <iostream.h>

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

void main()
{
int a=10,b=5;
cout<<min(a,b)<<'\n';
char p='A',q='Z';
cout<<min(p,q)<<'\n';
float z=1.91,x=3.98;
cout<<min(z,x)<<'\n';
}



Same Output. Nearly the same Executable size. But what we have achieved is that the time we take to type the code is reduced. The code looks more readable and incase there is an error just correcting it here will make the change for all data types accessing this function.

Let me explain what happens at compile time.When the Function us first called with this:


cout<<min(a,b);   //a and b are int's



It goes to the function min(). Now T is the value that will be substituted with the data type of the parameter. So here T will be int. So Dynamically the Function Declaration becomes like this...


int min(int a,int b)



In the second case T takes the form of a char and so on...The Compiler on every call still has to generate seperate functions for each data type but what we are saving are typing time and debugging ease.

Some of you might wonder....what if we want all data-types to access a templated function except one? Like for example in a abs() function we would like all data types to access it except a char data-type. What do we do then? Well in such acase we override the function call like this...


template <class T>
int abs(T no)
{
  return (no<0)?(no*-1):no;
}

void abs(char a){}



This way even if accidentaly a char data type is used as a parameter to the abs function..the overloaded function gets called...not the Templated version.

What if we wanted a multi-parametered Templated Function? Here is the Syntax


template <class T,class Q>
void function(T item,Q data){}



You now know enough of Function Templates.Now it's time to move onto Class Templates.

OK. 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&#91;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; 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()
{
//Code
}



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)
{
//code
}




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:public stack<T>
        {
         //members...
        };




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

Suggestions\Querys can be brought to my notice at born2c0de@hotmail.com

HAVE FUN CODING!!!






Discuss this in our Webmaster Forums

About The Author:
Sanchit Karve
Sanchit Karve is currently a Student in Mumbai who in his spare time devotes himself to programming. He knows quite a lot of languages including C/C++/Assembly/PERL/PASCAL/BASIC/MFCVC++ etc. He loves to teach programming and writes Tutorials/Articles/Code and submits them for people to learn from them.

Go To Top

This article has been read 423 times.


About This Author :: Request Reprint :: Print Article :: Tell A Friend



Advertising
Advertise your website here. View Advertising Information.






Wild West Domains
Icons
Unique and Professional XP Style Icons for use in websites, software and web based application.
Contact Information
SurfSpeedy

Powered by Outasight Enterprises Pty Ltd
PO Box 1218 Mudgeeraba QLD 4213 AUS
All content � Webmaster Resources 101, 2002-2005 unless otherwise stated.
Design by OE Design Hosted by Surf Speedy View our Privacy Policy
Page loaded in 1.883 secs.
14 users online.

The Hottest Reseller Program Going!