我想创建一种方法schedule_function
,该方法将指向BasicAlgo
对象的成员函数的指针保存到ScheduledEvent
中,但是没有在BasicAlgo
中定义该函数的父类Strategy
。现在,我正在使用此方法,该方法对于在Strategy
中保存函数非常有效,但不适用于BasicAlgo
函数:
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));
}}
我尝试将Strategy::*func
替换为Strategy*::*func
,但这导致了编译器错误,而且似乎不正确。
有什么方法可以将派生类BaseAlgo
的成员函数的指针作为参数{strong> 在基类Strategy
中,而无需在{中定义函数{1}}?
答案 0 :(得分:2)
您无法将BaseAlgo
的成员函数存储在指向Strategy
的成员函数的指针中。
您可以将BaseAlgo
的成员函数存储在指向BaseAlgo
的成员函数的指针中,并且可以在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);
}
否则,您可以使用诸如std::function
之类的类型擦除函数包装器代替函数指针。
答案 1 :(得分:2)
不可能将派生类函数指针存储在基类函数指针中。
另一种方法是存储带有Strategy*
参数的函数:
class Strategy {
...
void schedule_function(function<void(Strategy*)> func) {
heap_eventlist.emplace_back(std::make_unique<ScheduledEvent>(func));
}
};
然后,您可以直接使用Strategy的成员函数:
BasicAlgo g;
g.schedule_function (&BasicAlgo::f); // f is a member function of Strategy
但是您还可以提供任何其他接受Strategy指针作为参数的函数。如果您的策略是多态类,则可以尝试安全地向下转换Strategy
指针,并调用派生类的成员函数。
g.schedule_function ([](Strategy *x)->void {
BasicAlgo*b=dynamic_cast<BasicAlgo*>(x);
if (b) b->ff();
});
这里是demo。