Re: passing member function pointers to a function
tbringley@gmail.com wrote:
First things first. You're top-posting (i.e., posting above the text to
which you're replying rather than below or inline) and you seem to be
double posting as well. Both of things will make others less inclined
to help you. (To your credit, you've composed clear and thoughtful
questions, which is always appreciated.)
Thanks for the suggestions everyone. I guess what I had in mind was
something along the lines of:
class ode_solver{
...
double (*f) (double,double);
void solve();
...
};
ode_solver s;
s.f = & arbitraryclass.arbitraryfunction;
s.solve();
This would work perfectly fine if f pointed to a non-member function
-- and this idea is used a lot in C.
Indeed, but think about why this won't work for a member function.
Conceptually when you call member function A::f( x, t), you're really
making a call along the lines of f( A*, x, t) where A* is the "this"
pointer. As you suggested in your original post, f needs to have some
sort of local state and there's no way to make all of that local state
available to some other function if you only give it a function pointer.
I will be needing to use the ode_solver with an extremely general set
of functions f that might come from all different kinds of classes.
It is not an option to guarantee that f is a member of a particular
class or has a particular name (i.e. f or operator(double,double)). I
would much prefer if I didn't have to modify the code of
arbitraryclass, if that's possible.
Well that's understandable. In that case you might want to consider
some sort of adapter class that makes an arbitrary third party class
compatible with your solver. Again you can do this via templates or
inheritance, but basically you need wrap a reference to the third party
class inside of some standardized function object and specialize the
function object to call the third party class function. This may
involve some fairly gnarly syntax so I won't embarrass myself by trying
to write sample code on the spot :)
It seems like the suggestions are along the lines of that f should be
itself a class. So...
class ode_solver{
TwoArgFunc f;
};
but then...
class my_class{
TwoArgFunc f1;
...
};
No, my suggestion was that my_class derive from TwoArgFunc, not that it
contain such a function. But if you don't have access to the other
classes then this becomes a moot issue.
-Mark