Re: passing member function pointers to a function
Please note that my C++ is so rusty it squeaks when I walk.
On Feb 23, 10:36 pm, tbring...@gmail.com wrote:
I am interested in a way of having a class call a general
member function of another class.
Specifically, I am trying to write an ordinary
differential equation class that would solve a general
equation in the form: dx/dt = f(x,t).
I believe you're making a conceptual mistake here. In the
design you're describing f(x,t) is not represented by a
method of a class, but by the class itself, and f a (x,t) -
by an instance of the class representing f(x,t) functions.
That's why you probably shouldn't try passing a pointer to
a method, pass a reference to the object instead. If you
have more general questions about all of this, you probably
should follow-up to comp.object.
The ode class shouldn't know anything about f, except how
to call it.
That's pretty much a textbook description of an interface.
[...]
a member of the ode solver, but then I would have to
write a new ode solver for every new class of functions
to be used for f or to have all these derive from some
kind of base class, which I would prefer to avoid.
That kinda defeats the purpose of OOD, doesn't it?
My question is: is there a simple and elegant way to do
this? I would think that similar issues have been
encountered many times before.
I'm not sure if this will work for you, but consider this
bare-bones implementation:
#include <iostream>
class interface_function
{
public :
virtual double operator ( )
( double x , double t ) const = 0 ;
} ;
class ode
{
public :
static void solve ( const interface_function & f ) ;
} ;
void ode :: solve ( const interface_function & f )
{
std :: cout <<
f
(
static_cast < double > ( 1 ) ,
static_cast < double > ( 1 )
) ;
std :: cout << std :: endl ;
}
class f : public interface_function
{
public :
double a_ ;
f ( ) : a_ ( 1 ) { }
virtual double operator ( )
( double x , double t ) const ;
} ;
double f :: operator ( )
( double x , double t ) const
{
return t + x * a_ ;
}
class g : public interface_function
{
public :
double a_ ;
g ( ) : a_ ( 1 ) { }
virtual double operator ( )
( double x , double t ) const ;
} ;
double g :: operator ( )
( double x , double t ) const
{
return t - x * a_ ;
}
int main ( )
{
f f1 ;
g g1 ;
ode :: solve ( f1 ) ;
ode :: solve ( g1 ) ;
f1 . a_ = 5 ;
g1 . a_ = 5 ;
ode :: solve ( f1 ) ;
ode :: solve ( g1 ) ;
}
--
roy axenov