Page 310 - DCAP404 _Object Oriented Programming
P. 310
Unit 14: Advanced Concept in C++
14.1 Function of Templates Notes
In C ++ when a function is overloaded, many copies of it have to be created, one for each data
type it acts on. In the example of the max ( ) function, which returns the greater of the two values
passed to it this function would have to be coded for every data type being used. Thus, you will
end up coding the same function for each of the types, like int, float, char, and double. A few
versions of max ( ) are:
Int max ( int x, int y)
{
return x > y ? x : y
}
char max ( char x, char y )
{
return x > y ? > x : y
}
double max (double x , double y)
{
return x > y ? x : y
}
float max ( float x, float y)
{
return x > y ? x : y
}
Here you can see, the body of each version of the function is identical. The same code has to be
repeated to carry out the same function on different data types. This is a waste of time and effort,
which can be avoided using the template utility provided by C ++.
“A template function may be defined as an unbounded functions “ all the possible parameters to
the function are not known in advance and a copy of the function has to be created as and when
necessary. Template functions are using the keyword, template. Templates are blueprints of a
function that can be applied to different data types.
Notes The definition of the template begins with the template keyword. This is followed
by a comma-separated list of parameter types enclosed within the less than (<) and greater
than (>) signs.
Syntax of Template
Template < class type 1, type 2 ... >
Void function - name ( type 2 parameter 1, type 1 parameter 2 ) {...}
LOVELY PROFESSIONAL UNIVERSITY 303