5
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?

David G
  • 94,763
  • 41
  • 167
  • 253
Yoh0xFF
  • 1,450
  • 2
  • 18
  • 31
  • 1
    What about it? One use might be `std::sort(begin(arr), end(arr), std::greater());` to sort a container of integers from highest to lowest. – chris Aug 27 '12 at 18:37

3 Answers3

4
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);
log0
  • 10,489
  • 4
  • 28
  • 62
0

It's a template class that can be instantiated with one type argument. So you can say greater<int>, greater<my_class>, etc. Each of those instantiations has an operator() that takes two arguments of type const T& and returns the result of comparing them.

greater<int> gi;
if (gi(1, 2)) {
    // won't get here
} else {
    // will get here
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

I don't know have much you know about template programming and functors.

Let's start with functors :

struct greater {
  bool operator()(const int& x, const int& b) const {
    return x > y;
}

greater g;
g(2,3); // returns false
g(3,2); // returns true

So functors mock a function you could have as well implemented bool g(int x, int y){return x>y;} and used it the same way.

The nice thing about functors, is that you can also store some data when working on more complexe data structure.

Then there is the template part : you want to write the same functor for any type, you don't care if the type is an int, a float, a complexe object, the code will be the same. That's what the template part is for.

Tristram Gräbener
  • 9,601
  • 3
  • 34
  • 50