Consider the example
#include <iostream>
int big(into a,into b)
{
if(a>b)
return a;
else
return b;
}
float big(float a float b)
{
if(a>b)
return a ;
else
return b ;
}
int main()
{
cout<<big(4,5);
cout<<big(5.6,4.8);
}
On observing the above program we can notice that the big function is overloaded.
Instead of writing the whole big function again and again for each data type which is burden for user to write.
We can introduce template.
- template :
- is a keyword .
- two ways we can define template
- function template and class template.
template are mechanism that make it possible to use functions and class to handle many different data types.
Above program implemented using the template.
#include <iostream >
template <class X>
X big(X a,x,b)
{
if(a>b)
return a ;
else
return b ;
}
int main()
{
cout <<big(4,5);
cout <<big(4.56,8.54);
}