// The template function compare, and a number of applications (most are OK, some lead to compile time errors). #include #include #include "point.h" class ComparsionProblem{}; template int compare(const T &v1, const T &v2){ if (v1 < v2) return -1; else if (!(v1 < v2) && !(v2 < v1)) // better than v1 == v2 return 0; else if (v2 < v1) // better than v1 > v2 return 1; else throw ComparsionProblem(); } int main(){ using namespace std; // Comparing int, infers the type automatically: cout << compare(1,2) << endl; // -1 cout << compare(1,1) << endl; // 0 cout << compare(2,1) << endl; // 1 cout << endl; // Passing type parameteter explicitly: cout << compare(1,2) << endl; // -1 cout << compare(1,1) << endl; // 0 cout << compare(2,1) << endl; // 1 cout << endl; string s1 = "abe", s2 = "katten", s3 = "abe"; // Comparing strings: cout << compare(s1,s2) << endl; // -1 cout << compare(s2,s1) << endl; // 1 cout << compare(s1,s3) << endl << endl; // 0 cout << endl; // Comparing C-style strings: cout << compare("ABE","KAT") << endl; // 1. Wrong. Why? Because we compare pointers... cout << compare("KAT","ABE") << endl; // -1. Wrong. cout << compare("kat","katten") << endl; // error: no matching function for call to // compare(const char [4], const char [7]) // Comparing Points (without having defined < on Point): Point p1(1,2), p2(3,4); int i = compare(p1, p2); // error: no match for operator< in v2 < v1 // error: no match for operator< in v1 < v2 // error: no match for operator< in v2 < v1 }