// template7.cpp By: Aiman Hanna - ©1993-2006 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 indicate it as "typename" instead of "class", // which gives a feeling 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 #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; } 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); // min( c1, c2 ); // The above line would also be illegal, but for a different reason. What is it? // Hint: Have we overloaded the '<' operator to work for the Car class? 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 */