Class member function calling external function with another class member function as an argument to the external function

This is my class:

class Exact : public Solver {
public:
Exact();
Exact(const Exact& orig);
virtual ~Exact();
void solve() override;
private:
double fn(double);
};
============================================================
This is my external function:
double root(double (*func)(double), const double x1, const double x2, const double tol)
============================================================
I am calling Exact::solve from main().
Exact::solve calls the external function root(double (*func)(double), const double x1, const double x2, const double tol) with Exact::fn(double) as its first argument.
============================================================
I tried many things (commented codes below) with all errors.
void Exact::solve() {
//double (Exact::*pmf)(double);
//auto pmf = fn;
//std::function<double (double)> pmf = &Exact::fn;
//double temp = root(pmf, 0.0, 100.0, 0.000001);
//std::function<double (double)> f1 = Exact::fn;
//double (*pmf) (double) = fn;
//std::function<double (double)> pmf = &Exact::fn;
double temp = root(pmf, -100.0, 0.0, 0.0000001);
}
=============================================================

It seems the pointer pmf is a pointer to class::member_function, whereas root takes as its 1st argument pointer to a function. But I am not sure how to resolve this issue. Thanks for any help!
> It seems the pointer pmf is a pointer to class::member_function, whereas root takes as its 1st argument pointer to a function.
yes, the difference being that a member function has an additional parameter: the this pointer.

> But I am not sure how to resolve this issue.
if you do not intend to use the status of the caller object, consider making `fn()' an static member function
Yeah, I tried making fn() static and that worked. But fn() could not use any non-static data members of Exact class, which is problematic. If needed, root declaration can be changed to take a pointer to class::member_function. But not sure how to go about doing that.
> But fn() could not use any non-static data members of Exact class
that's why I prefixed the suggestion with
"if you do not intend to use the status of the caller object"

given that you do want to pass a non-static member function, you'll also need to provide an object to act on.
1
2
3
4
5
6
7
double root( double (Exact::*f) (double), Exact &object, ... ){
   (object.*f)( 42 );
}

Exact::solve(){
   root( &Exact::fn, *this, ... );
}


The thing is that now root() is quite specific, it only works with member functions of the Exact class.
Last edited on
Topic archived. No new replies allowed.