CPP Program On Template - WAY2IT

Latest Post :

CPP Program On Template


Program to demonstrate calling a function Template


#include<iostream.h>
#include<conio.h>
template <class A>
A sum(A x,A y)
{
return x+y;
}
void main()
{
clrscr();
int a,b;
cout<<"Enter two integers=";
cin>>a>>b;
float f1,f2;
cout<<"Enter two float=";
cin>>f1>>f2;
cout<<"\n\nsum of two integers"<<sum(a,b);
cout<<"\n\nsum of two float"<<sum(f1,f2);
getch();
}


Function templates : - Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

●▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬


Program to demonstrate calling a function Template
 with multiple Parameters



#include<iostream.h>
#include<conio.h>

template <class A,class B>

A large(A x,B y)

{

if(x>y)

return x;

else
return y;
}
void main()
{
clrscr();
int n=10;
float f=22.67;
cout<<"\n\n Largest no(22.67,10)="<<large(f,n);
int m=50;
cout<<"\n\n Largest no(22.67,50)="<<large(f,m);
getch();
}

A template parameter :-  is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function. These function templates can use these parameters as if they were any other regular type.