Function Templates (cont.)
•Intemplate<classT>,"class"means"type",or
"classification“.ItisNOTtheclasswelearned
before
•Toavoidconfusion,onecanuse“typename”.
•Tcanbereplacedbyanytypeintheruntime,
predefinedoruser-defined(likeaC++classtype),
infunctiondefinitionbody
•Note:onecanuseothersymbolthan"T",butTis
the"traditional"usage
How Does this Work?
•Consider the following example
#include <iostream.h>
template<typenameT>
T abs(T x)
{return x < 0? -x : x;}
void main()
{intn = -5;
double d = -5.5;
cout<< abs(n) << endl;
cout<< abs(d) << endl;
return;
}
How Does this Work? (cont.)
Outputis:
5
5.5
•Ifnotusingtemplate,atleasttwoabsfunctions
needtobedefined:
–oneforinttype,
–otherfordoubletype
•Inrun-time,compilerdeterminestheactualtype
forTbasedonthetypeoftheinputvariable
How Does this Work? (cont.)
•Forinstance,abs(n),nisinttype
•Thecompilerthencreatesthefollowingfunction
basedonthetemplate
intabs(intx)
{returnx<0?-x:x; }
•Forinstance,abs(n),nisdoubletype
•Thecompilerthencreatesthefollowingfunction
basedonthetemplate
doubleabs(doublex)
{returnx<0?-x:x; }
Difference Between Template
Functions and Normal Functions
•Compilerwon’tgenerateinstancefortemplate
functionsduringcompiling.Itgenerateswhenitis
called(seeabsexample).
•Ifatemplatefunctionisusedbyseveralother
placesindifferent.cppfiles,thetemplatefunction
anditsbodyneedtobeputinthe.hfilenotonly
thedeclaration.
•Thefunctionpointercanonlypointtoinstanceof
thetemplatefunction
Back to the max function
•Wenowcanusetemplatetoaddressourissue
withthemaxfunction
#include<iostream.h>
template<classT>
Tmax(Tx,Ty)
{returnx>y?x:y;}
voidmain()
{intn1=-5,n2=0;
doubled1=-5.5,d2=-5.9;
cout<<max(n1,n2)<<endl;
cout<<max(d1,d2)<<endl;
}
Swap values example
#include <iostream.h>
class ABC
{
private:
float x, y;
public:
ABC(float inx, float iny)
{x=inx; y=iny;}
};
template<class T>
T swap(T &x, T &y)
{T tmp= x;x = y;y = tmp;}
Swap values example (cont.)
void main()
{intn1 = -5, n2 = 0;
double d1 = -5.5, d2 = -5.9;
ABC obj1(3, 4.4),obj2(3.1, 0.2);
swap(n1, n2);
swap (d1, d2);
swap (obj1, obj2);
}
We can also use it to swap the values of two objects.
Multiple Type Parameters
•Canhave:template<classT1,classT2>
•NottypicalUsuallyonlyneedone"replaceable"
typeCannothave"unused"templateparameters
Eachmustbe"used"indefinitionErrorotherwise
Multiple Type Parameters (cont.)
•What is the problem of the following
template functions?
template<class T1, class T2>
T1 max (T1 num1, T1 num1)
{return num1 > num2 ? num1 : num2;}
T2 min (T2 num1, T2 num2)
{return num1 > num2 ? num2 : num1;}
•First example T2 is not used.
•Second example Missing a template prefix
What is the output of the following program?
#include <iostream.h>
template<class T>
T max(T x, T y)
{return x > y? x : y;}
void main()
{intn1 = -5, n2 = 0;
double d1 = -5.5, d2 = -5.9;
cout<< max(n1, d2) << endl;
cout<< max(d1, n2) << endl;
}
•Compiling error. T ambiguous…
•How to fix it?
–Use multiple type parameters
Class Templates
•Wecanalsodefinetemplateclass,whichcanbe
consideredasthe“generalized”classes(i.e.,canbe
usedtogenerateactualclassesinrun-time).
template<classT>
classClassName
{//Tdatamember;
//memberfunctiondefinition;
};
•Example
template<class T>
class calc
{public:
T multiply(T x, T y);
T add(T x, T y);
};
template<class T>
T calc<T>::multiply(T x, T y)
{ return x*y; }
template<class T>
T calc<T>::add(T x, T y)
{ return x+y; }
Templates and Inheritance
•NothingnewhereDerivedtemplateclasses
Canderivefromtemplateornon-template
class
•Derivedclassisthennaturallyatemplate
classSyntaxsameasordinaryclassderived
fromordinaryclass
Summary Function templates
Class templates
•Define functions with parameter for a type
Class templates
•Define class with parameter for class
are template classes
•Can define template class derived from a
template base class