c++ - How to call a function from any class by a pointer to it? -
i'm building engine. need create timer
class call function pointer separate class. example:
class mytimer { public: void settimeoutfunction( _pointer_, unsigned short timeoutms ) { // here need have opportunity store _pointer_ function } void ticktimer() { ... // here need call function pointer ... } }; // main class: class myanyclass { public: void start() { mytimer mytimer; mytimer.settimeoutfunction( startthisfunc, 1500 ); // 1500ms = 1.5s while ( true ) { mytimer.ticktimer(); } } void startthisfunc() { ... } }
in summation, how store pointer function belongs class , call function pointer?
for requirements, might recommend making timer class template:
template <typename t> struct mytimer { using funcptr = void (t::*)(); mytimer(funcptr ptr, t * obj, unsigned int timeout_ms) : ptr_(ptr), obj_(obj), timeout_ms_(timeout_ms) {} void ticktimer() { (obj_->*ptr_)(); } funcptr ptr_; t * obj_; unsigned int timeout_ms_; };
usage:
struct myanyclass { void start() { mytimer<myanyclass> mytimer(&myanyclass::startthisfunc, this, 1500); while (true) { mytimer.ticktimer(); } } void startthisfunc() { /* ... */ } };
Comments
Post a Comment