Passing Types (Instead of Fixed Types) void swap (T& first, T& second) T temp- first first second second temp i
void swap (T& first, T& second) { T temp = first; first = second; second = temp; } Passing Types (Instead of Fixed Types)
Using function overloading, note how similar each of the swap functions would be The three places where the type is specified What if we passed the type somehow? Templates make this possible Declare functions that receive both data and types via parameter Thus code becomes more generic Easier to reuse and extend to other types
▪ Using function overloading, note how similar each of the swap functions would be • The three places where the type is specified ▪ What if we passed the type somehow? ▪ Templates make this possible • Declare functions that receive both data and types via parameter ▪ Thus code becomes more generic • Easier to reuse and extend to other types
Function Templates Produce overloaded functions that perform identical operations/algorithms on different types of data Programmer writes a single function-template definition Compiler generates separate object-code functions(function template specializations) based on argument types in calls to the function template Generate and compile declaration or definition? compiler does more things
Function Templates Produce overloaded functions that perform identical operations/algorithms on different types of data • Programmer writes a single function-template definition • Compiler generates separate object-code functions (functiontemplate specializations) based on argument types in calls to the function template Generate and compile, declaration or definition? compiler does more things …
General Form of Template template<typename T> Function Definition with the parameter type T T is a type-parameter(placeholder)naming the"generic"type of value(s)on which the function operates Function Definition is the definition of the function, using type T Can use 'class'or 'typename, so it is a type name, so 'typename'is better than the old'class
General Form of Template template<typename T> Function Definition with the parameter type T … Can use ‘class’ or ‘typename’, so it is a type name, so ‘typename’ is better than the old ‘class’! ▪ T is a type-parameter (placeholder) naming the "generic" type of value(s) on which the function operates ▪ Function Definition is the definition of the function, using type T
template<typename T void swap (T& first, T& second) T temp first first second; second tempi (){ int a, bi double x,y char mni swap(a, b)i// swap<int>(a, b) swap(x, y)i// swap<double>(x, y) swap(m, n)i// swap<char>(m, n)i
template<typename T> void swap (T& first, T& second) { T temp = first; first = second; second = temp; } main() { int a,b; double x,y; char m,n; swap(a,b); // swap<int>(a,b); swap(x,y); // swap<double>(x,y); swap(m,n); // swap<char>(m,n); }