clearfix
clearfix

Reputation: 467

Function-pointer to comparison operator

I'm currently trying to grasp both function overloading and function pointers. In order to shorten a piece of code I want/need to make a function pointer to a comparison operator. In my original code i loop trough and compare lots of pairs of float variables. My actions after the comparison is dependent on wether a third semi-static variable is positive or negative. In this version i either have to check the value of the semi-static variable for every pair or I have to replicate a lot of code.

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]>
  }
}

If I instead could evaluate angleRight once and then store a function-pointer to either operator> or operator<, I would be able to use this function-pointer instead and could avoid evaluating angleRight as well as the entire 'else'-block. I have tried to understand function pointers and (I think) I see how I could have managed if i wanted access to an overloaded member-function.

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

But what i really want to do/imagine is something like this:

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

EDIT: Making the two functions 'greater' and 'less' does what I want:

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;

But it annoys me that I actually have to write the functions. Is there no way of directly accessing the float-operator> ?

Upvotes: 0

Views: 946

Answers (1)

orlp
orlp

Reputation: 117661

The C++ way of doing things like this is not by accepting a function pointer, but by accepting a function-like object.

An example:

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);
}

In this example we don't care exactly what Cmp is, as long as it supports operator() with two operands.

If your function accepts a function-like-object you can use standard objects like std::less automatically too solving this question.

Upvotes: 1

Related Questions