Function templates can be used to create a common function to support multiple different parameters and avoid repetitive design of function bodies that overload functions. The most important feature of this is the function of the practical data type as a parameter.
The general form of defining a function template is:
Template<typename t>
Or
Template<class t>
1 Let's try to use function overloading to define different types of functions
Int:
int int_add (int a,intb)
{
int C;
c = a + B;
return C;
}
Double
Double Double_add (double a;double b)
{
Double C;
c = a + B;
return C;
}
int main ()
{
Cout<<int_add (5,3) <<endl; Call the Int_add function
Cout<<double (5.1,3.1) <<endl; Call the Double_add function
return 0;
}
2 Also we can use constructors to do the same things
#include <iostream>
using namespace Std;
int n_add (int a,int b)//define function N_add for int type data addition
{
int C;
C=a+b;
return C;
}
Double N_add (double a,double b)//define function N_add for double type function addition
{
Double C;
C=a+b;
return C;
}
int main ()
{
Cout<<n_add (5,3) <<endl; Call the N_add function
Cout<<n_add (5.35,5.5) <<endl; Call the N_add function
return 0;
}
3 Using Function templates
#include <iostream>
using namespace Std;
Template<typename t>
T N_add (t a,t b)
{
T C;
c = a + B;
return C;
}
int main ()
{
Cout<<n_add (5,3) <<endl;
Cout<<n_add (5.1,3.1) <<endl;
return 0;
}
C + + (use of function templates)