// template7.cpp By: Aiman Hanna - ©1993-2005 Aiman Hanna // This program illustrates more on template functions. // Since the type that a template defines, can be a primitive type, such as int, // it might be more appropriate to create indicate it as "typename" instead of "class", // which gives a felling that the type is of a class type. // Hence, the first line of a template function may alternatively, and preferably, // look like: // template // instead of // template // In addition the program illustrates what happens if a call to a template function // includes invalid or potentially ambiguous parameters. // Key Points: 1) typename #include template Type min( Type a, Type b ) { return a < b ? a : b; // same as: if ( a < b ) return a; else return b; } class Car { public: Car() {}; }; 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; // The following calls would be illegal, however // cout << " The minimum value of the two values x and w is: " << min( x, w ) // << endl << endl; // The above line would result in: /* error C2782: template parameter 'Type' is ambiguous, could be 'double' or 'int' */ Car c1, c2; // min( c1, c2 ); // The above line would also be illegal since there is no definition of the '<' operator 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 */