C++"更大"的函数对象定义

Yoh*_*xFF 5 c++ stl

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

我在STL库中找到了"函数对象类的大于不等式比较"的定义.有人可以向我解释这段代码是如何工作和编译的吗?

log*_*og0 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
  }
};
Run Code Online (Sandbox Code Playgroud)

这是定义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;
};
Run Code Online (Sandbox Code Playgroud)

这允许您访问定义binary_function的类型

greater<int> op;
greater<int>::result_type res = op(1,2);
Run Code Online (Sandbox Code Playgroud)

这相当于

std::result_of<greater<int>>::type res = op(1,2);
Run Code Online (Sandbox Code Playgroud)