0gap 0gap - 1 year ago 77
C++ Question

Multiple pointers to class methods

I have a class which should hold a pointer to methods of various classes and call them via it.

Something like here but with a small -or maybe not- difference. Those various other methods are not overloaded.


Derived1 d1;
OtherClass* handlerInst = new OtherClass();
handlerInst->Add( &d1, &(Derived1::method1) );

I want to pass whatever member method of class types derived from base.

Is this possible somehow?


The idea is that OtherClass is a thread(not standard c++ thread). Some code of other classes(Derived1, derived2...)-it is not mandatory to have a common base class- can thus must be run only after this thread has ended its run.
I am hoping to see if i can add methods with whatever name.
Also being a thread has nothing to do with this. It can be a simple class which when it ends its method it runs some code from other classes.

Answer Source

I'm assuming these functions also return the same type (I've gone with void in this example).

You don't say whether the functions are overrides of virtual functions declared in base - you mention they are not overloads, but if they are not overrides then the existence of base doesn't really help here.

If they do exist in base then you can try the following:

#include <vector>
class OtherClass 
    using FunctionPtrType = void(Base::*)();
    std::vector<std::pair<Base*, FunctionPtrType>> m_Collection;


   void Add(Base* object, FunctionPtrType pMemberFunction)
       m_Collection.emplace_back(object, pMemberFunction);

   void CallAll()
       for(auto item : m_Collection)

calling example

Derived d1;
OtherClass holder;
holder.Add(&d1, &Base::Func);

If on the other hand the functions do not override virtual functions in base, then I have another solution involving a wrapper class, which I can post if the above doesn't work for you.