Question

Is it possible to do something like this? Without using static functions or make chordL a member of power. I really don't understand how to do that, could it be not possible?

class power {
  double b;     

public:
  void set(double par){b=par}     

  double fun(double arg){
    return b*pow(arg,2); 
  } 

  double execute(double par1, double par2);
};

double chordL(power::*fm, double p1, double p2){      // it's not a member function
  return sqrt(pow(fm(p1)-fm(p2),2)+pow(p1-p2,2));  // clearly doesn't work! 
}

double power::execute(double par1, double par2){     // it's a member function
  double (power::*g)(double);
  g=&power::fun;
  return chordL(g,par1,par2);
}
Was it helpful?

Solution

You can't do that. A member function (that isn't declared static) has a special/hidden argument of this. If you have an object of the correct type, you can pass that along with the function, and call it using the obscure syntax needed for member function calls:

 double chordL(power* tp, double (power::*fm)(double), double p1, double p2)
 ...
     (tp->*fm)(p1); 


double power::execute(double par1, double par2){     // it's a member function
  double (power::*g)(double);
  g=&power::fun;
  return chordL(this, g,par1,par2);
}

Edit: added calling code, passing this to the chordL function, and swapped the order of the object and the function pointer from previous post - makes more sense to pass this as the first argument. And I fixed up the function pointer argument.

OTHER TIPS

You need an instance of power to call the function pointer on like this:

double chordL(T& instance, T::*fm, double p1, double p2){
    return sqrt(pow(instance.*fm(p1) - instance.*fm(p2), 2) + pow(p1 - p2, 2));
}

When calling a member function, you need to specify the object it has to be called on. You need to pass this pointer to chordL as well, and call the function like this:

template<class T>
double chordL(T* t, double (T::*fn)(double), double p1, double p2)
{
    return sqrt(pow((t->*fn)(p1) - (t->*fn)(p2), 2) + pow(p1 - p2, 2));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top