Elegant solution for pointer-to-a virtual member function to functionpointer

A

Anonimo

Hello,

I would like to see a cleaner solution than the one I have written in
the example below for passing a pointer-to-a-virtual member function of
an abstract class to a function pointer.

/*
* Suppose this is the interface provided as API by an external library
* written in C, containing the pointer to a function to be called by
* the library itself.
*/
struct S {
void *o;
void (*callback)(S* p);
};

#include <iostream.h>

/*
* This is my abstract class with the virtual member function.
*/
class A {
public:
virtual void f() = 0;
static void wrapper(S* p) {((A*)(p->o))->f();};
};

/*
* These are derived classes.
*/
class B : public A {
void f() {cout << "B::f() called\n";};
};
class C : public A {
void f() {cout << "C::f() called\n";};
};

S s;
A* a;

int main(int argc, char**argv) {

// dynamic linking
if (argc > 1)
a = new(B);
else
a = new(C);

s.callback = A::wrapper;
s.o = a;

//...

s.callback(&s); // dynamic behaviour in the library

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top