指向比较运算符的函数指针

时间:2012-03-28 12:53:53

标签: c++ function-pointers

我目前正在尝试掌握函数重载和函数指针。 为了缩短我想要/需要创建一个指向比较运算符的函数指针的代码。在我的原始代码中,我循环使用并比较了许多浮点变量对。 比较后我的行为取决于第三个半静态变量是正还是负。在这个版本中,我要么必须检查每对的半静态变量的值,要么我必须复制很多代码。

double angleRight; //This variable is either positive or negative and is not reassigned for the purpose of this code

while (points.size() > 2){
siz = points.size();
for (int i = 0; i < siz; i++){
  if (angleRight > 0 && points[i].angle < 0){
<Do something>
    <remove points[i]>
  } else if (angleRight < 0 && points[i].angle > 0){
  <Do something else>
      <remove points[i]>
  }
}

如果我可以评估angleRight一次,然后将函数指针存储到任一运算符&gt;或者运算符&lt;,我可以使用这个函数指针代替,并且可以避免评估angleRight以及整个'else'块。 我试图理解函数指针和(我认为)我知道如果我想访问一个重载的成员函数我可以如何管理。

//This compiles
class Bs{
  public:
  float x;
  bool operator< (Bs y){
    return x < y.x;
  }
};
bool (Bs::*compare) (Bs) /*const*/ = &Bs::operator<;

但我真正想做/想象的是这样的事情:

//This does not compile:
bool (*compar) (float) /*const*/ = &float::operator<;

修改 让两个函数“更大”和“更少”是我想要的:

bool greater(float x, float y){
  return x > y;
}
bool less(float x, float y){
  return x < y;
}

bool (*compar) (float, float) = (angleRight < 0)? &greater : &less;

但令我很生气的是,我实际上必须编写这些函数。有没有办法直接访问浮点运算符&gt; ?

1 个答案:

答案 0 :(得分:1)

C ++这样做的方式不是通过接受函数指针,而是通过接受类函数对象

一个例子:

template <class T, class Cmp> int cmp(T x, T y, Cmp cmp_func = std::less) {
    return cmp_func(x, y) - cmp_func(y, x);
}

在这个例子中,我们并不关心Cmp究竟是什么,只要它支持operator()两个操作数。

如果你的函数接受类似函数的对象,你可以自动使用像std::less这样的标准对象来解决这个问题。

相关问题