Sunday, June 2, 2019

Generic Functions : Template

Template

Used for generic programming.

Generic : - Generalized not bound with particular data type when we use method overloading , it will increase the size of the class . to avoid this , we use template.

Template types:

Function Template : -

 We can define function with generic template

Class template : -

We can define generic class .

Advantage :-

Reduce the size of code .
Better performance.

#include<iostream.h>
#include<conio.h>
template <class T>
T  highest(T n ,T m)
{
          if(n>m)
                   return n;
          else
                   returm m;
}
void main()
{
          clrscr();
          int  a=567;
          int  b=345;
          cout<<hight(a,b);
          cout<<highest(45.56f,34.64f)
          getch();
}



         Class Template: -

         #include<iostram.h>
         #include<conio.h>
         class a
          {
              private:
                       T  x;
              public:
                   a(T  r)
                   {
                             x=r;
}
void display()
{
          cout<<”value of x::”<<x;
}
         };
        void main()
        {
              clrscr();
               a <int> p(78);
               p.display();
               a <char> k(a);
               k.display();
               getch();
         }

No comments:

Post a Comment