Copyright © Curt Hill Generic Functions Separating Data Type from Logic
Copyright © Curt Hill Consider The swap function is often used in sort functions: void swap(float &a,float &b){ float temp; temp = a; a = b; b = temp; } How is this different than a double swap function?
Copyright © Curt Hill Double Swap The double swap is exactly the same except that three instances of float would have to be replaced by double If the C preprocessor were a bit stronger, we could do this with it As it is C++ was enhanced with the template feature to allow this
Copyright © Curt Hill The template swap The swap function as a generic: template void swap(T & a, T & b){ T temp; temp = a; a = b; b = temp; } T is the generic type –It may be any type suitable for assignment
Copyright © Curt Hill Using the generic swap The client code would look like this: int i,j; double x,y;... swap(i,j); swap(x,y); The signature matching process will make the correct function
Copyright © Curt Hill Discussion Client code can not distinguish from overloaded function names and template functions Figuring out which function will actually receive the call: Given function call: x(y) –Where x is the function name –Where z is the argument type –where is some declaration: z y; though it does not have to be explicit
Copyright © Curt Hill Process First look for an exact match among non- template functions: –type x(z y); –If found call it Next look for a function template that if generated with type z could produce an exact match: –template type x(T y) {...} –The generated function must match exactly –Not even trivial conversions will be applied (ie a value parameter must match in type exactly, widening etc. is not applied) Next look for conversions that allow a non template function to work
Copyright © Curt Hill Discussion The runtime effect is exactly the same as if several versions of the function existed Conceptually easy once function name overloading is in place The reserved word in the brackets may be typename or class The type used in the function must be suitable for the kind of operations that are performed in the function
Copyright © Curt Hill Discussion of example In this example assignment only is needed –Arrays and strings may not be assigned so could not be the type –Several objects disallow assignment as well, such as ifstreams and ofstreams In the context of a sort a comparison would be required –Structs and classes are not usually suitable for greater or less comparison –However, overloading these operators works the same as if the type naturally had the operation