// MaxTmpt2.cpp - Another example of defining a template function. // This version elimiates the error in the first version, by // instantiating "max(int, int)". Notice how a call to max(int,int) // doesn't "instantiate" max(int,int) so later calls to max(int,char) // could find it. You must explictly instantiate max(int,int). // Note too the use of the "typename" keyword instead of "class". // These keywords can be used interchangably here. // // Written by Wayne Pollock, Tampa Florida 2000 #include #include using namespace std; template< typename T > T max ( T a, T b ) { if ( a > b ) return a; else return b; } int main () { cout << setprecision( 2 ) << setiosflags( ios::fixed | ios::showpoint ); float f1 = 1.1, f2 = 2.2; float f3 = max( f1, f2 ); cout << f3 << endl; // Prints "2.20" int x = 1, y = 2; cout << max( x, y ) << endl; // Prints "2" char ch = 'a'; int z = max ( x, ch ); // This matches "int max(int, int)". cout << z << endl; // Prints "97". return 0; }
Send comments and mail to the WebMaster. |