Wednesday, 5 October 2011

Template function and Template class in C++

        Template function is a generic type function which is supported to all data types.  It is used to avoid the repetition.

For Example:
         We want to write function to find the maximum number from given two numbers.  The given number may be integer,long or any type.  By using the classic method we must write separate function for integer and long.

int findMax(int a,int b)
{
   int result=(a>b)?a:b;
   return(result);
}

log findMax(long a,long b)
{
   long result=(a>b)}a:b;
   return result;
  }

int main()
{
    int a=10,b=20;
    long x=8.7,y=9.08;
    cout<<findMax(a,b);
    cout<<findMax(x,y);
    return 1;
 }

      We have two functions in the above code both are same except the data type to avoid this repetition we will using the Template function.

template <class myType>
myTytpe findMax(myType a,myType b)
{
   myType result=(a>b)?a:b;
   return result;
}

int main()
{
    int a=10,b=20;
    long x=8.7,y=9.08;
    cout<<findMax(a,b);
    cout<<findMax(x,y);
    return 1;
 }

Template Class 
       Template class is an generalized class. Which is the extension of the template function we can use the generic data type in the whole class i.e more than one function and declare the properties with the template data type.

Example


      I want to create a stack for the integer and string in the classic approach a separate class for integer and separate class for string.  Except the data type remaining all are same.

Like following program


       class IntegerStack 
       {
        public:
         IntegerStack() { top = -1; }
        void push(int i)
          { stack[++top] = i; }
        int pop()
          { return stack[top--]; }
        private:
          int top;
          int stack[100];
       };

       class StringStack {
public:
StringStack() { top = -1; }
void push(string i)
           { stack[++top] = i; }
          string pop()
          { return stack[top--]; }
       private:
          int top;
          string stack[100];
       };

     we will template class instead of this classic approach

template <class T>
class Stack {
     public:
       Stack();
       void push(T i);
       T pop();
     private:
      int top;
      T st[100];
     };

    template <class T>
     Stack<T>::Stack()
     {
      top = -1;
     }

   template <class T>
   void Stack<T>::push(T i)
    {
     st[++top] = i;
    }

   template <class T>
   T Stack<T>::pop()
    {
     return st[top--];
    }

   int main()
{
  Stack<int> integer;
  Stack<string> string;
  integer.push(10);
  string.push("sugunthan");
}




No comments:

Post a Comment