C ++“更大”的函数对象定义

时间:2012-08-27 18:35:26

标签: c++ stl

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

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

3 个答案:

答案 0 :(得分: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
  }
};

这里是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;
};

这允许您访问定义binary_function

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

相当于

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

答案 1 :(得分:0)

这是一个模板类,可以使用一个类型参数进行实例化。所以你可以说greater<int>greater<my_class>等。每个实例都有一个operator(),它接受两个类型为const T&的参数,并返回比较它们的结果。

greater<int> gi;
if (gi(1, 2)) {
    // won't get here
} else {
    // will get here
}

答案 2 :(得分:0)

我不知道你对模板编程和仿函数了解得多。

让我们从仿函数开始:

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

因此,仿函数模拟了一个函数,你可以实现bool g(int x,int y){return x&gt; y;}并以相同的方式使用它。

关于仿函数的好处是,在处理更复杂的数据结构时,您还可以存储一些数据。

然后是模板部分:你想为任何类型编写相同的仿函数,你不关心类型是int,float,complexe对象,代码也是一样的。这就是模板部分的用途。