// greater.cpp - demonstrates a function template // cmc, 11/22/2010 #include using std::cout; using std::endl; using std::ostream; // greater(x, y) - returns reference to greater of x or y // assumption: operator> is defined for type T template T const &greater(T const &x, T const &y) { return (x > y) ? x : y; } class Double { // simple wrapper class to test greater for user-defined type public: friend bool operator> (Double const x, Double const y) { return x.value > y.value; } friend ostream &operator<< (ostream &out, Double const &d) { return out << d.value; } Double(double d = 0) : value(d) { } private: double value; }; int main() { // let compiler deduce a couple of primitive types cout << greater(1, 2) << endl; // T is int cout << greater('a', 'A') << endl; // T is char // let compiler deduce a user-defined type - T is Double cout << greater(Double(5.62), Double(3.48)) << endl; // mix types by telling the compiler how to convert them cout << greater(17, 'A') << endl; // T is char cout << greater (17, 'A') << endl; // T is int cout << greater('a', 'A') << endl; // T is int }