Title:Function overloading and templated functions Tapestry Sect. 11.2 for templated functions Horton pp.
Description:
causes code bloat: each instantiation of a function (for a diff. ... (when suitable) since in this case there is no code duplication or code bloat! ... – PowerPoint PPT presentation
Title: Function overloading and templated functions Tapestry Sect. 11.2 for templated functions Horton pp.
1 Function overloading and templated functions Tapestry Sect. 11.2 (for templated functions) Horton pp. 350-377 (templated classes) Templated classes Tapestry Chapter 13 (but skip most for now) 2 Aim
Say you need variations of the same basic function
one to sort an array of integers and one to sort an array of characters
one to swap two variables of type int one to swap two vars. of type char
one to find the maximum element of an array of ints one for array of strings
...
You can
define two different functions taking different types of arguments
(function overloading)
use a templated function which uses a templated type
3 Function overloading
Define two different functions that take the appropriate parameter types
void Sort(tvectorltintgt a) void Sort(int a int size)
... ...
void Sort(tvectorltstringgt a) void (string a int size)
... ...
4 Function overloading
Define
void Sort(tvectorltintgt a)
...
void Sort(tvectorltstringgt a)
...
The appropriate function will be called depending on the parameter. E.g.
Tvector ltintgt nums
Tvector ltstringgt names
sort(nums) //calls the first function
sort(names) //calls the second function
This may at times be the right solution in some cases. But function overloading duplicates code
maintaining is difficult (2-3 versions of a sort function)
5 Function overloading
By the way you cannot do this with
int FindRoots(double a double b double c)
double FindRoots(double a double b double c)
Why
Because from the types of the parameters passed you cannot determine which function should be called
The signatures of two different functions should not be completely the same (parametersname)
6 Templated functions
simple form for ints
void Swap(int a int b)
int temp
temp a
a b
b temp
template ltclass Typegt
void Swap(Type a Type b)
Type temp
temp a
a b
b temp
Any name can be the template parameter (e.g. Type MyType ...)
7 Templated functions more complex
How can we swap the values at the given locations of a tvector
template ltclass Tgt //note changed Type to T
void Swap(tvectorltTgt list const int i const int j)
T temp
temp listi
listi listj
listj temp
In short everywhere you had a type (e.g. int) you put a new type name (e.g. T) and add template ltclass typenamegt at the beginning of the function.
8 Templated functions more complex
template ltclass Typegt
void Print(tvectorltTypegt list)
int i count
count list.Size()
for (i0 i lt count i)
cout ltlt listi ltlt endl
9 Templated functions general form
template ltclass Tgt void DoStuff(T myvar)
template ltclass Typegt
Type FindLastElement(tvectorltTypegt list1)
template ltclass T1 class T2gt
int CompareLists(tvectorltT1gt list1 tvectorltT2gt list2)
//note that we have two types (T1 and T2)
// in general you can have as many types as you need variable types in your function
10 function overload vs templated functions comparison (Tapestry pp 543)
Function overloading duplicates code
maintaining is difficult (2-3 versions of a sort function)
must each be changed if there is a need
Function templates
reuses code rather than duplicate it
causes code bloat each instantiation of a function (for a diff. type) adds new object code hence the name template
Func. Templates are like macros...
You should also consider reusing simple functions with casting as a 3rd alternative (when suitable) since in this case there is no code duplication or code bloat!
Define
void Swap (double a double b )
Use with ints as
int a b
Swap( (double)a (double)b )
You should use this option when the types are so easily convertable! 11 Function objects 12 Function objects Advanced
Function objects (functors)
What if we want to sort sometimes according to length of strings sometimes to lexical order etc.
If we write multiple versions of the same function (cant use templated function for this) you have code duplication possibly for each sort algorithm
Solution Pass a function object as a parameter to the function syntactically equivalent to passing a function
the object class should have a comparison function
this public member function of the object will be used inside the called program
13
//sortall.cpp
template ltclass Typegt
void SelectSort(tvectorltTypegt a int size)
// precondition size of elements of a
// postcondition a is sorted
// standard selection sort
int jkmin
for(j0 jlt size-1j)
min j
for(kj1 kltsize k)
if (ak lt amin)
min k
Default Selection Sort function called when the user calls SelectSort with only two parameters 14
//sortall.cpp
template ltclass Typeclass fobjgt
void SelectSort(tvectorltTypegt a int size const fobj comp)
// precondition size of elements of a
// postcondition a is sorted
// standard selection sort - except for diff. comparison method
int jkmin
for(j0 jlt size-1j)
min j
for(kj1 kltsize k)
if (comp.compare(akamin) lt 0)
min k
Selection Sort function that will be called when the user calls SelectSort with three parameters one of which is the comparer object 15
class StrLenComp
public
int compare(const string a const string b) const
// post return -1/1/0 as a.length() lt b.length()
if (a.length() lt b.length()) return -1
if (a.length() gt b.length()) return 1
return 0
int main()
string word filename PromptString(filename )
tvectorltstringgt wordvec
StrLenComp slencomp
int k
ifstream input(filename.c_str())
16 Note that you can have one SelectSort that you call with 3 parameters such that the last one indicates the type of comparison to be done and the SelectSort function acts accordingly E.g.
SelectSort(tvectorltTypegt a int size string comptype)
...
if (comptype lexical)
//sort in lexical order
else
//sort by word length
main ()
...
string lexcomp lexical
string lengthcomp length
SelectSort(wordvec wordvec.size() lexcomp)
SelectSort(wordvec wordvec.size() lengthcomp)
...
17
E.g. Tapestry sortstocks.cpp
The SelectSort code in this approach would be
You would have to pass a parameter even when most of the time we want the default behavior
Using a function object you can put the details of the actual sort in a class function of its own
18 Function pointers 19
As a related topic functions can be passed as parameters to other functions
use pointers to pass a function as a parameter to another function
20 Pointers to functions
include ltiostream.hgt
int addition (int a int b)
return (ab)
int subtraction (int a int b)
return (a-b)
int operation (int x int y int (fptr)(intint))
int g
g (fptr)(xy)
return (g)
int main ()
int mn
m operation (7 5 addition)
//...
n operation (810 subtraction)
cout ltltn
return 0
21
Much more info can be found at
http//www.newty.de/fpt/index.html
22 Templated Classes 23 Templated Classes
The linked list class should be able to be used for integers or strings ...
Tapestry tvector is a templated class
tvectorltintgt myintarr(1000)
tvectorltstringgt mystrarr(1000)
...
Similar to templated functions
24 Templated Classes
template ltclass T)
class LinkedList
public
...
void InsertOrdered(T value)
...
You can start with a fixed type (as we did in homework 1) and later change your class to a templated one
25 Templated classes
//
/ default class destructor. it is called automatically and deallocates list if
programmer forgot to deallocate the list himself /
templateltclass Typegt
LinkedListltTypegtLinkedList()
ifdef _DEBUG
cout ltlt Destructor called\n
endif
//...
26
/ prints list contents /
templateltclass Typegt
void LinkedListltTypegtPrintList(void)
Node tmphead
while(tmp!NULL)
coutltlttmp-gtvalueltlt
tmptmp-gtnext
coutltltendl
int main()
/ code to test the linked list class /
LinkedListltintgt list
list.InsertOrdered(3) list.PrintList()
list.DeleteNode(3)
list.PrintList()
list.InsertOrdered(7) list.PrintList()
...
27
templateltclass Typegt
class LinkedList
public
LinkedList()
LinkedList()
void DeleteList()
void PrintList()
void DeleteNode(Type val)
void InsertOrdered(Type num)
...
private
struct Node
Type value
Node next
Node(Node link const Type info)
value(info)next(link)
Node head //version that does NOT use a dummy header do not use in your hw
28 Misc. templated classes
Templated classes (Tapestry page 628)
compiler needs to access both .h and .cpp when instantiating a templated class as in templated functions
.h must include .cpp or
define your functions inline within the class
Read lectures/week3-templated/templated-class-issu es.doc to better understand templated classes better and avoid compilation problems when you write templated classes
About PowerShow.com
PowerShow.com is a leading presentation/slideshow sharing website. Whether your application is business, how-to, education, medicine, school, church, sales, marketing, online training or just for fun, PowerShow.com is a great resource. And, best of all, most of its cool features are free and easy to use.
You can use PowerShow.com to find and download example online PowerPoint ppt presentations on just about any topic you can imagine so you can learn how to improve your own slides and presentations for free. Or use it to find and download high-quality how-to PowerPoint ppt presentations with illustrated or animated slides that will teach you how to do something new, also for free. Or use it to upload your own PowerPoint slides so you can share them with your teachers, class, students, bosses, employees, customers, potential investors or the world. Or use it to create really cool photo slideshows - with 2D and 3D transitions, animation, and your choice of music - that you can share with your Facebook friends or Google+ circles. That's all free as well!
For a small fee you can get the industry's best online privacy or publicly promote your presentations and slide shows with top rankings. But aside from that it's free. We'll even convert your presentations and slide shows into the universal Flash format with all their original multimedia glory, including animation, 2D and 3D transition effects, embedded music or other audio, or even video embedded in slides. All for free. Most of the presentations and slideshows on PowerShow.com are free to view, many are even free to download. (You can choose whether to allow people to download your original PowerPoint presentations and photo slideshows for a fee or free or not at all.) Check out PowerShow.com today - for FREE. There is truly something for everyone!