regarding template in OOP

hi friends, i am not clear with template in oops concepts .will anyone explain its basic things in this topic.

Replies

  • friendster7
    friendster7
    TEMPLATES IN C++






    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 examples now.One without
    Templates and one with Templates.Here is the first program.



     [quote]#include 
    
    using namespace std;
    
    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;
    }
    
    
    int main()
    {
     int a=10,b=5;
     cout<Function Overloading doesn't help much as far as typing time and source space isconcerned.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 
    
    using namespace std;
    
    template 
    T min(T a,T b)
    {
      return (a < b)?a:b;
    }
    
    int main()
    {
     int a=10,b=5;
     cout<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<
    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 a
    case we override the function call like this...

     template 
    int abs(T no)
    {
      return (no<0)?(no*-1):no;
    }
    
    void abs(char a){}
    This way even if accidentally 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 
    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            // For sleep()
    #include      // For I/0
    #include      // FOR MessageBox() API
    #include 
    
    using namespace std;
    
    #define MAX 10        // MAXIMUM STACK CONTENT
    
    template     // 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;ia;    // 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:"< Everything looks similiar except an object declaration
    stack 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 
            stack ::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  stack ::func(int data)
            {
            //code
            }
            
    Templates can also have pre-defined values like this:
             template 
            class stack
            {
              private:
              T data[max];
              //rest of the members...
            };
    Templates can be inherited as well like this:
             class newstack:public stack
            {
             //members...
            };
            
    That's all about templates.If you use Templates Frequently you will save
    a lot of typing and debugging time.
  • salaikumar
    salaikumar
    hi my dear friend it is nice and useful for me.thank a lot.hate's of to u .

You are reading an archived discussion.

Related Posts

😕 i m doing engg. in I.T. in third year.plz help me in seminar on latest technology related to computer .or any other technical field.plz as soon as possible................ thankx...................
Name: HORO *Engineering Trade: Electromechanical Location: MEXICO *Occupation: Half time employee and Automation Consultant Work Experience: 20 years of experience *Hobbies & Interests: Robotics, Autonomous vehicles, music *I joined CrazyEngineers...
I need to make a mini project by next week.I belong to ECE and studying first year,and need some help to do that.I am given a max of 10 components.So...
hi friends, I am yet another crazy engineer joining dis group... I m yami doing my 3rd year cse.... let us all discover things together and we l try to...
Quick Check on IELTS Exams IELTS : International English Language Testing System. [Frequently Asked Questions] ADMINISTERED BY : IELTS is adminstered by University of Cambridge Local Examination Syndicate (UCLES), British...