// template2.cpp By: Aiman Hanna - ©1993-2002 Aiman Hanna // This program illustrates template functions. The "template" keyword always // begins the definition of a template function. If there is forward declaration // for the function, the "template" keyword must also be there. Following the // "template" keyword, there is a list of what is called a "formal type // parameters". The list of formal type parameters is surrounded by the "<" and // ">" characters. A comma separates the different formal types. So, examples of // the first line of a template function may look like: // template // or // template // Notice that the "class" keyword must precede each type. The following for // example is illegal: // template // // Each of the types "int", "double", "char", as well as arrays and linked lists // are valid actual parameter types that can substitute the formal parameters. // // The name of the formal type parameters can occur only once within the formal // list. The following, for example, is illegal: // template // However, the same name can legally be used within the formal list of other // template functions. // // The program shows an example of a template function that replaces all the // three "min()" overloaded functions in template1.cpp. // // Key Points: 1) template functions. #include // template functions that has one formal type, called "Type". // (Notice that this is just a name that can be anything different than "Type"). // The function expects two parameters of type "Type". The function finds and // returns the smaller value of the two passed values. Hence, the return type // of the template function is also "Type" as well. template Type min( Type a, Type b ) { return a < b ? a : b; // same as: if ( a < b ) return a; else return b; } int main( ) { int x = 10, y = 5; double w = 13.2, z = 21.9; char ch1 = 'f', ch2 = 'k'; cout << " The minimum value of the two integers x and y is: " << min( x, y ) << endl << endl; cout << " The minimum value of the two doubles w and z is: " << min( w, z ) << endl << endl; cout << " The minimum value of the two characters ch1 and ch2 is: " << min( ch1, ch2) << endl << endl; return 0; } // The output of the program /* The minimum value of the two integers x and y is: 5 The minimum value of the two doubles w and z is: 13.2 The minimum value of the two characters ch1 and ch2 is: f */