Templates
2 minute read
TEMPLATES
1.
What are
function templates? What is the need for the function templates? Give example.
v
Function
template is used to create a family of functions with different argument types.
v
A
function template may be simple, overloaded or member function.
v
Function
template is needed when we want to perform a different task with the same name
of function.
v
In
function overloading we have to define and declare as many functions with the
same name as we need for different task with possible matches.
v
A
function created from a template is called function template.
v
We
define a function,
add (int a, int
b);
for
adding two integer values.
v
But
now, if we want to add two float values we can do this by simply replacing the
appropriate int declarations with float in the add function this means that we
have to redefine the entire function all over again.
v
The
function template is used in this situation, in that we define an add()
function with the data type as a parameter and then use this function to create
an add ()Include function for any data type instead of defining a new function
every time.
v
For
example: A swap () function template that will swap two values of a given type
of data.
#include <iostream.h>
template <class T>
void swap(T &X , T &Y)
{
T temp = X;
X = Y;
Y = temp;
}
void fun (int m, int n, float a, float
b)
{
cout << “m
and n before swap: “<< m <<” , “ << n << “\n”;
swap (m, n);
cout << “m
and n after swap: “<< m <<” , ” << n << “\n”;
cout << “a
and b before swap: “<< a <<” , ” << b << “\n”;
swap (a, b);
cout << “a
and b after swap: “<< a <<” , ” << b << “\n”;
}
int main ()
{
fun
(100,200,11.22,33.44)
return
0;
}
v
The
output of Program 12.4 would be:
m
and n before swap: 100 , 200
m
and n after swap: 200 , 100
a
and b before swap: 11.22 , 33.439999
a
and b after swap: 33.439999 , 11.22
2.
How is a
function template overridden for a specific definition for its templates?
v
In
a function template we define only one function as the generic function.
v
In
this we pass the data type as an argument.
v
The
function is overridden as per the call of function and its argument.
v
For example: swap ()
function for swapping two values,
template
<class T>
void swap (T
&X, T&Y)
{
T temp = x;
X = Y;
Y = temp;
}
v
It
we call the function swap () with the argument as
swap (m, n);
Where m and n are integers and values are 10 and 20 respectively.
v
In
that the type T is referred as integer and then swaps the value of integer.
v
If
we pass the value float as,
swap (a, b);
where a and
b are float with value 10.5
and 20.5 in that it makes the T type as float and overrides the function and
swaps two float value.
3.