Saturday, June 17, 2023

Templates

 

Templates

In C++ ,in this below program function overloading program.same max() function for each data type like int,float,char,double.The same code repeated on different data type. This will lead to waste of time and effort.To solve this complexity by using template facility.

#include<iostream.h>

#include<conio.h>

int  max(int  a,int b)

{

return (a>b)?a:b;

}

float  max(float  a, float  b)

{

return (a>b)?a:b;

}

char  max(char  a, char  b)

{

return (a>b)?a:b;

}

void main()

{

clrscr();

cout<<max(20,30)<<endl;

cout<<max(20,30)<<endl;

cout<<max(20,30)<<endl;

getch();

}

Syntax

template <class type>

 

#include<iostream.h>

#include<conio.h>

template<class T>

T max(T  x,T  y)

{

return (x>y)?x:y;

}

void main()

{

clrscr();

cout<<max(17,19)<<endl;

cout<<max(1.5,6.7)<<endl;

cout<<max(‘A’,’B’)<<endl;

getch();

}

Output

19

6.7

B

 

#include<iostream.h>

#include<conio.h>

template<class T,class W>

void  max(T x , W  y)

{

if(x>y)

{

cout<<x<<”is greater than”<<y<<endl;

}

else

{

cout<<x<<”is less than”<<y<<endl;

}

}

void main()

{

clrscr();

cout<<max(10,5.6)<<endl;

cout<<max(‘A’,4.5)<<endl;

getch();

}

Output

10 is greater than 5.6

is greater than 4.5

0 comments:

Post a Comment