Yoh0xFF Yoh0xFF - 1 month ago 5
C++ Question

C++ "greater" function object definition

template <class T> struct greater : binary_function <T, T, bool> {
bool operator() (const T& x, const T& y) const {
return x > y;
}
};


I found this definition of "Function object class for greater-than inequality comparison" in STL library.
Can somebody please explain to me how this code works and compiles?

Answer
template <class T> // A template class taking any type T
// This class inherit from std::binary_function
struct greater : binary_function <T, T, bool>
{
  // This is a struct (not a class).
  // It means members and inheritens is public by default

  // This method defines operator() for this class
  // you can do: greater<int> op; op(x,y);
  bool operator() (const T& x, const T& y) const {
    // method is const, this means you can use it
    // with a const greater<T> object
    return x > y; // use T::operator> const
                  // if it does not exist, produces a compilation error
  }
};

here is the definition of std::binary_function

template <class Arg1, class Arg2, class Result>
struct binary_function {
  typedef Arg1 first_argument_type;
  typedef Arg2 second_argument_type;
  typedef Result result_type;
};

this allows you to access the types defining the binary_function

greater<int> op;
greater<int>::result_type res = op(1,2);

which is equivalent to

std::result_of<greater<int>>::type res = op(1,2);