4.1 C++ Template for engineering course. Learn easily

kk6369150094 36 views 23 slides Jul 12, 2024
Slide 1
Slide 1 of 23
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23

About This Presentation

Cpp templates


Slide Content

C++ Templates
ManimalaK
Assistant Professor
Department of Computer Science and Engineering
Government College of Engineering, Salem

Introduction
•Ageneraldefinitionoffunctionsandclasses
–GenericclassesandGenericfunctionsprovides
supportforGenericprogramming
–Furthersimplifiesthepreviousfunction
overloading
–Anotherformofpolymorphism
–Inatemplate,thedatatypeistheparameter
–Theprecisedefinitionsofthetemplatefunctions
andclassesaredeterminedinrun-timebasedon
thedatatype

Function Templates
•Todefinefunctiontemplatesusedtocreatea
familyoffunctionswithdifferentargumenttypes.
•Considerthefollowingfunction
intmax(intx,inty)
{return(x>y?x:y);}
•Itonlyworksfortheinttypeofvariables
•Howcanwemakeitworkforothertypesof
variables?

Function Templates (cont.)
•Use function overloading
float max (float x, float y)
{return (x > y? x : y);}
double max (double x, double y)
{return (x > y? x : y);}
char max (char x, char y)
{return (x > y? x : y);}
……

Function Templates (cont.)
•Dowehaveasmarterwaytodothat?
•Firstlinecalled"templateprefix“
template<classT>
Tmax(Tx,Ty)
{return(x>y?x:y); }
•TypeparameterFirstlinecalled"templateprefix“
Tellscompilerwhat’scomingis"template“.And
thatTisatypeparameter

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; }

void main()
{calc<int> c1;
cout<<c1.multiply(10,20);
cout<<c1.add(100,200);
calc<float> c2;
cout<<c1.multiply(10.50,20.75 );
cout<<c1.add(100.66,200.77);
}

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

Exercise
•Writetemplatefunctiontoaddthreenumbersand
oneuserdefineddatatype.
•Writeatemplatefunctiontosortthenumbersand
oneuserdefineddatatype.
•WriteaclasstemplateforVectortofindmaximum,
minimumandsum.
•WriteaclasstemplateforArraytoread,display
andsortmethods.

Thank You…
Tags