c++ - 指向比较运算符的函数指针

标签 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 求值一次,然后将函数指针存储到 operator> 或 operator<,我将能够使用这个函数指针来代替,并且可以避免对 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;

但是让我烦恼的是我实际上必须编写函数。有没有办法直接访问 float-operator> ?

最佳答案

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 来解决这个问题。

关于c++ - 指向比较运算符的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9907938/

相关文章:

c++ - Vim:公共(public)关键字的对齐方式

c++ - Libusb如何从端口读取字符

c++ - 理论 - 如何判断元素是否重叠?

c++ - 为什么使用 'cpp' 编译这个简单的 C++ 程序会失败?

c++ - 嵌入 Python 并向解释器添加 C 函数

android - JNI - 从 jstring 到 byte、从 byte 到 string 的传输问题

c - 如何将函数指针分配给函数

c - C 中的函数指针相等

c - ISO C Void * 和函数指针

c - 将函数指针传递给 pthread_create 函数的 arg