Slimelite BBS

pointers to member functions

Back to EMULATE

From Jerry Coffin · 1996-04-10 16:33 · #73593 in EMULATE

In reply to pointers to member functions by Marcel Schepers

On (08 Apr 96) Marcel Schepers wrote to All...

 MS> Hello,
 MS> I am faced with a typical C++ problem. I wrote a DLL (I am working in
 MS> MS-Windows) with a function which is declared as: 

 MS> void FAR PASCAL _export bs(float y[], int nv, void (*derivs)(float,   
 MS>      float *, float *));

 MS> The DLL consists of no OOP techniques. It is merely a collection of
 MS> good working C code. In my main window class, a child of TWindow
 MS> (Borland OWL 1.0), I declared the following public function:

 MS> virtual void TBlackHoleWindow::Derives(float Sigma, float X[], float
 MS> dXdS[]);

Your basic problem is that there's a fundamental and irreconcilable
difference between a pointer to a function and a pointer to a member
function.  You have a couple possibilities for dealing with this, the
most common being to make the whatever::Derives() member a static member
function.  However, this means that it will not have direct acess to
class member variables.  It's not clear whether this is actually
required or not - Derives should usually depend only on its arguments,
in which case not be able to access class instance variables isn't
really a problem.

Ultimately, if you're going to do this sort of thing much in C++, and
you have source to the DLL in question, it may be easier to change the
function taking a pointer to a function into a base class with a pure
virtual function that you derive from, with each derivation specifying
the Derives function it needs to use.

class bs {

    float *y;
    int nv;

public:

    virtual void Derives() = 0;
};

class TBlackHole : public bs {

public:

    void Derives() {
        // whatever it needs in its version of Derives.
    }
};

Another possibility is to use templates instead of derivation.  This
will often improve efficiency (since the function used doesn't have to
be virtual) but also often increases program size since whatever code
`bs' uses will typically get duplicated in each instantiation.  It's
also possible to use a combination of templating and derivation.  For
instance, you might want to make both the type and size of y template
parameters, so you can make your class work with doubles instead of
floats, when needed.  OTOH, if it's clear that only floats will ever be
useful, this may simply complicate things without accomplishing
anything useful.
    Later,
    Jerry.

... The Universe is a figment of its own imagination.

--- PPoint 1.90
 * Origin: Point Pointedly Pointless (1:128/77.3)