Is it a "good idea" to reinterpret a member function pointer?
I have a workflow that contains a list of Flow Actions and works through them as when.
template <class T> class ThreadAction
{
public:
typedef void (T::*action)();
ThreadAction(T* t, action f) :
func(f),obj(t) {}
void operator()() { (obj->*func)(); }
void (T::*func)();
T* obj;
};
This is usually called
myActionThread->addAction(
new ThreadAction<TheirClass>(this, &TheirClass::enable)
);
Which worked fine so far
void TheirClass::enable()
was changed to
bool TheirClass::enable()
Unfortunately, we cannot change it again, because other things need a new format (and overloads cannot differ only in return type).
I tried
myActionThread->addAction(
new ThreadAction<TheirClass>(this,
reinterpret_cast<void(TheirClass::*)>(&TheirClass::enable)
)
);
Everything seems to work fine, but I'm not sure if re-interpreting a function pointer like this is "certain" behavior, can anyone advise?
source to share
This is definitely not a supported behavior and may cause your program to crash.
Basically, you need to create a wrapper for TheirClass::enable()
that will have the correct return type. A simple one-liner is enough:
public:
void enableWrapper() { enable(); };
Then call:
myActionThread->addAction(
new ThreadAction<TheirClass>(this, &TheirClass::enableWrapper)
);
If you cannot directly modify TheirClass
, then create a simple subclass or helper class that implements the wrapper.
source to share
Not a good idea. Consider adding an extra template parameter for the return type:
template <class T, typename RetType> class ThreadAction
{
public:
typedef RetType (T::*action)();
ThreadAction(T* t, action f) :
func(f),obj(t) {}
RetType operator()() { return (obj->*func)(); }
RetType (T::*func)();
T* obj;
};
This is a return void application .
source to share