将派生 Class 函数的指针存储在基 Class 中
Store Pointer to Derived Class Function in Base Class
我想创建一个方法 schedule_function
,它将指向 BasicAlgo
object 的成员函数的指针保存到 ScheduledEvent
中,但没有定义该函数在 BasicAlgo
的 parent class、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
但这导致了编译器错误,而且它似乎不正确。
有什么方法可以从派生的 class BaseAlgo
中得到一个指向成员函数的指针作为参数 in base class , Strategy
, 没有在 Strategy
?
中定义函数
无法将 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
而不是函数指针。
无法将派生的 class 函数指针存储在基 class 函数指针中。
另一种方法是使用 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 指针作为参数的任何其他函数。如果您的策略是多态 class,则您可以尝试安全地向下转换 Strategy
指针并调用派生的 class 的成员函数。
g.schedule_function ([](Strategy *x)->void {
BasicAlgo*b=dynamic_cast<BasicAlgo*>(x);
if (b) b->ff();
});
这里是demo。
我想创建一个方法 schedule_function
,它将指向 BasicAlgo
object 的成员函数的指针保存到 ScheduledEvent
中,但没有定义该函数在 BasicAlgo
的 parent class、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
但这导致了编译器错误,而且它似乎不正确。
有什么方法可以从派生的 class BaseAlgo
中得到一个指向成员函数的指针作为参数 in base class , Strategy
, 没有在 Strategy
?
无法将 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
而不是函数指针。
无法将派生的 class 函数指针存储在基 class 函数指针中。
另一种方法是使用 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 指针作为参数的任何其他函数。如果您的策略是多态 class,则您可以尝试安全地向下转换 Strategy
指针并调用派生的 class 的成员函数。
g.schedule_function ([](Strategy *x)->void {
BasicAlgo*b=dynamic_cast<BasicAlgo*>(x);
if (b) b->ff();
});
这里是demo。