// template4.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // This program provides more information on template functions. The program shows // additional examples of template functions, where there is more than one formal // type, and when the passed arguments to the function include something more // than just a simple type (for example, an array). // // Key Points: 1) template functions. #include // Template functions that has two formal types, called "T" and "U". The // function expects two parameters. Each of the parameters can be either an // integer, or a double. The functions "min" finds the smaller of the two // values and returns it as a double value. // You should notice that this function is not that flexible, in the sense that // the return type is always double, instead of a template type. template double min( T a, U b ) { return a < b ? double(a) : double(b); // cast the return value to double } // template function that finds an returns the minimum value in an array. The // second parameter to the function indicates the range of the array to be // checked. The size of the passed array is assumed to be more than the passed // range. template T mininarr( const T arr[], int range ) { T min_value = arr[0]; for (int i = 1; i <= range; i++) if( arr[i] < min_value ) min_value = arr[i]; return min_value; } int main( ) { int i1 = 10, i2 = 12; double d1 = 13.2, d2 = 1.9; char ch1 = 'f', ch2 = 'k'; int intarr[8] = {12, 5, 7, 3, 2, 4, 5, 9}; double dblarr[6] = {2.7, 3.2, 4.9, 9.4, 1.1, 7.2}; char chararr[10] = {'s', 'd', 'l', 'k', 'o', 'p', 'e', 's', 'u', 't'}; cout << " The minimum value of i1 & d2 is: " << min( i1, d2 ) << endl << endl; cout << " The minimum value of d2 & i2 is: " << min( d1, i2 ) << endl << endl; cout << " The minimum value of d1 & d2 is: " << min( d1, d2 ) << endl << endl; cout << " The minimum value of i1 & i2 is: " << min( i1, i2 ) << endl << endl; // We can still compare characters, but must cast here otherwise the function will // just show the ASCII value of the character cout << " The minimum value of ch1 & ch2 is: " << char(min( ch1, ch2 )) << endl << endl; cout << " The smallest value in the first 6 elements in intarr is: " << mininarr(intarr, 5) << endl << endl; cout << " The smallest value in the first 4 elements in dblarr is: " << mininarr(dblarr, 3) << endl << endl; cout << " The smallest value in the first 10 elements in chararr is: " << mininarr(chararr, 9) << endl << endl; return 0; } // Note: If you compile in HP-UX, use +a1 to compile. Nothing to be done for VC++ // The output of the program /* The minimum value of i1 & d2 is: 1.9 The minimum value of d2 & i2 is: 12 The minimum value of d1 & d2 is: 1.9 The minimum value of i1 & i2 is: 10 The minimum value of ch1 & ch2 is: f The smallest value in the first 6 elements in intarr is: 2 The smallest value in the first 4 elements in dblarr is: 2.7 The smallest value in the first 10 elements in chararr is: d */