我目前正在尝试掌握函数重载和函数指针。 为了缩短一段代码,我想要/需要制作一个指向比较运算符的函数指针。在我的原始代码中,我遍历并比较了很多对浮点变量。 比较后我的行动取决于第三个半静态变量是正还是负。在这个版本中,我要么必须检查每一对的半静态变量的值,要么我必须复制大量代码。
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/