// template8.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // This program fixes one of the problems that template7.cpp has. // Notice the addition of the overloaded '<' operator for the Car class. // Key Points: 1) typename #include #include "template7.h" template Type min( Type a, Type b ) { return a < b ? a : b; // same as: if ( a < b ) return a; else return b; } // Definition of the Car class Car::Car(double pr) { price = pr; } void Car::setPrice(double pr) { price = pr; } // Since this function should NOT modify the class attributes, // it should be declared as a constant function double Car::getPrice() const { return price; } bool operator<( const Car& c1, const Car& c2) { // returns true if the price of c1 is smaller than the price of c2; // returns false otherwise if (c1.getPrice() < c2.getPrice()) return true; else return false; } int main( ) { int i1 = 10, i2 = 5; double d1 = 13.2, d2 = 21.9; char ch1 = 'f', ch2 = 'k'; cout << " The minimum value of the two integers i1 and i2 is: " << min( i1, i2 ) << endl << endl; cout << " The minimum value of the two doubles d1 and d2 is: " << min( d1, d2 ) << 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 i1 and d1 is: " << min( i1, d1 ) // << endl << endl; // The above line would result in: /* error C2782: template parameter 'Type' is ambiguous, could be 'double' or 'int' */ Car c1(3000), c2(7000); cout << " The cheapest price of the two cars, c1 and c2, is: " << min( c1, c2 ).getPrice() << endl << endl; // Hint: You should notice the syntax of the aboive line very carefully return 0; } // The output of the program /* The minimum value of the two integers i1 and i2 is: 5 The minimum value of the two doubles d1 and d2 is: 13.2 The minimum value of the two characters ch1 and ch2 is: f The cheapest price of the two cars, c1 and c2, is: 3000 */