// Explicit use of a functor, as you might use it INSIDE a container. #include #include using namespace std; // Compare two doubles according to how close they are to 5.0. // This does NOT sort anything! This merely compares two elements, // and returns true iff the first one should come before the second one. // Sure, this could be a template functor, but we don’t need that generality. // // As written, 4.0 and 6.0 are “equal”, so either one might come first. // It might be better to also have a secondary comparison based on value // if the proximity to 5.0 is equal, so 4.0 would come before 6.0. // // Always declare operator() const, if you can. Compilers are getting // fussier about requiring such a comparison functor for set and map. class Proximity { public: bool operator()(double a, double b) const { return fabs(a-5.0) < fabs(b-5.0); } }; template void decide(double m, double n) { const Compare cmp; // An object of the functor type if (cmp(m, n)) cout << m << " goes before " << n << "\n"; else if (cmp(n, m)) cout << n << " goes before " << m << "\n"; else cout << m << " and " << n << " are equal\n"; } int main() { decide(1,3); decide(9,9); decide(2,8); // How on Earth are 2 and 8 “equal”? }