Title: Function overloading and templated functions Tapestry Sect' 11'2 for templated functions Horton pp'
1Function 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)
2Aim
- 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)
- 2. use a templated function which uses a
templated type
3Function 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 Sort
(string a, int size) - ... ...
4Function 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)
5Function overloading
- Also, 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)
6Templated 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, ...)
7Templated 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.
8Templated 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
-
-
9Templated 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
10function 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 - (i.e. each call to the function using 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 NOR 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!
11Templated Classes
12Templated Classes
- Similar to the idea of a templated function, you
can have templated classes. - Similar to templated functions, these provide
type flexibility in class definitions. - For instance, the linked list class should be
able to be used for integers or strings, ... - e.g. Tapestry tvector is a templated class
- tvectorltintgt myintarr(1000)
- tvectorltstringgt mystrarr(1000)
- ...
13Templated Classes
- template ltclass Tgt
- class LinkedList
-
- public
- ...
- void InsertOrdered(T value)
- ...
-
-
- Write your class ADDING template ltclass Tgt
before each class and member function, and use
the given name as your type
14Templated 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
- //...
-
15- / prints list contents /
- templateltclass Typegt
- void LinkedListltTypegtPrintList(void)
-
- Node tmphead
- while(tmp!NULL)
- coutltlttmp-gtvalueltlt" "
- tmptmp-gtnext
-
- coutltltendl
-
- int main()
-
- / code to test a templated linked list class /
- LinkedListltintgt list
- list.InsertOrdered(3) list.PrintList()
-
- list.DeleteNode(3)
- list.PrintList()
- list.InsertOrdered(7) list.PrintList()
- ...
-
16- templateltclass Typegt
- class LinkedList
-
- public
-
- LinkedList()
- LinkedList()
-
- void DeleteList()
- void PrintList()
- void DeleteNode(Type val)
- void InsertOrdered(Type val)
- ...
-
-
- private
- struct Node
-
- Type value
- Node next
- Node(Node link, const Type v)
- value(v),next(link)
-
-
-
- Node head
//version that does NOT use a dummy header do
not use in your hw -
17Misc. templated classes
- Templated classes (Tapestry page 628)
- Compiler needs to access both .h and .cpp when
instantiating a templated class, as in templated
functions! - A templated class implementation (linkedlist.cpp)
cannot be compiled because it consists of
templated functions. - When linkedlistltstringgt is seen in the client
code (e.g. main.cpp), the compiler will reach the
definition of linkedlist class through
linkedlist.h, but not its member functions. So it
will assume the member functions are compiled
elsewhere and will be linked later, but they
arent and eventually the linker will complain. - Solution
- .h must include .cpp (BETTER) OR
- define your functions inline within the class
definition if they are very small functions - class myclass
-
- private
- string myname
- public
- void PrintName() //inline function
- cout ltlt myname //this is another way
of making //functions inline -
-
18END OF CLASS
19Function objects
20Function 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
21- //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 j,k,min
-
- 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
22- //sortall.cpp
- template ltclass Type,class 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 j,k,min
-
- for(j0 jlt size-1j)
-
- min j
- for(kj1 kltsize k)
-
- if (comp.compare(ak,amin) 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
23- 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())
-
24Note 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)
- ...
25- 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
26Function pointers
27- 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
28Pointers 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)(int,int)) -
- int g
- g (fptr)(x,y)
- return (g)
-
- int main ()
-
- int m,n
- m operation (7, 5, addition)
- //...
- n operation (8,10, subtraction)
- cout ltltn
- return 0
-
29- Much more info can be found at
- http//www.newty.de/fpt/index.html