Member Callback Functions

C

cadull

The aim of the following code is to store and call member functions on an
object.

class C {};

class CF
{
public:
template<typename T> inline CF(T& o, void (T::*f)())
: pO(&o), pF( (void (C::*)()) f) {};

inline void Call() { (pO->*pF)(); };

void (C::*pF)();
C* pO;
};

class A : public C
{
public:
void F() {};
};

int main()
{
A a;
CF f(a, A::F);
f.Call();
}

Objects of type CF will be stored in an array (or container) and may call
functions from different classes. Performance and memory comparisions with
virtual functions would depend on usage.

My question: since class C appears to have little impact other than allowing
compilation, can this be written without C? What other alternatives are
there (with type generic storage)?

Regards,
cadull
 
C

cadull

Moving the cast up a level (to a structure containing the function pointer)
removes the need for A to extend C. This provides the interface I'm after.
Possible improvements?

class CF
{
public:
class C {};

template<typename T> class D
{
public:
inline D(T& o, void (T::*f)())
: pO(&o), pF(f) {};

void (T::*pF)();
T* pO;
};

template<typename T> inline CF(T& o, void (T::*f)())
: d( (D<C>&) D<T>(o, f)) {};

inline void Call() { (d.pO->*d.pF)(); };

D<C> d;
};

class A
{
public:
void F() {};
};

int main()
{
A a;
CF f(a, A::F);
f.Call();
}
 

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

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top