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?

+2


source to share


4 answers


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.

+9


source


Err, from what I understand, you chose a method that returns a bool

method that returns void

?



This can be dangerous, depending on the call / return convention used. You may forget to print the return value or override the register value with the return value.

+2


source


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 .

+2


source


I usually find that when the question is of the form "Is _______ a good idea?" the answer is almost always "NO!"

This is probably true out of context.

+1


source







All Articles