Search code examples
c++pointersinheritancepolymorphismmember

Store Pointer to Derived Class Function in Base Class


I want to create a method schedule_function which saves a pointer to a member function of a BasicAlgo object into a ScheduledEvent, but not have said function defined in BasicAlgo's parent class, Strategy. Right now I am using this method which works fine for saving functions in Strategy but will not work for BasicAlgo functions:

class Strategy {

schedule_function(void (Strategy::*func)()) {
    // Puts the scheduled event built with the strategy function onto a list
    heap_eventlist.emplace_back(std::make_unique<events::ScheduledEvent>(func));
}}

I tried replacing Strategy::*func with Strategy*::*func but that caused compiler errors and it doesn't seem correct.

Is there any way to have a pointer to a member function from derived class BaseAlgo as a parameter in the base class, Strategy, without defining the function in Strategy?


Solution

  • There's no way you can store a member function of BaseAlgo in a pointer to member function of Strategy.

    You can store a member function of BaseAlgo in a pointer to member function of BaseAlgo, and you can use such pointer type with CRTP:

    template<class T>
    struct Strategy {
        void schedule_function(void (T::*func)());
    };
    
    struct BasicAlgo : Strategy<BasicAlgo> {
        void memfun();
    };
    
    int main() {
        BasicAlgo b;
        b.schedule_function(&BasicAlgo::memfun);
    }
    

    Otherwise, you could use a type-erasing function wrapper such as std::function instead of a function pointer.