Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Pointer to Derived Class Function in Base Class [duplicate]

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?

like image 592
Evan Kirkiles Avatar asked Jul 26 '26 23:07

Evan Kirkiles


1 Answers

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.

like image 111
eerorika Avatar answered Jul 29 '26 14:07

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!