mercredi 4 août 2021

How to bind all kind of function to a timer?

I have a simple timer, which i want to execute my function after a fixed time.

the code is:

#include <thread>
typedef void (*callback)();
class timer {
 public:
   virtual ~timer() {
     if(t_) {t_->detach(); delete t_;}
   }
   void start(int sec, callback f) {
     t_ = new std::thread([&sec, &f]() {sleep(sec); f();});
   }
  std::thread * t_;
};

void test () {
  printf("here called\n");
}
int main() {
  timer t;
  t.start(3, test);  // TODO: test is ok, but it wont work
  // if test is a class member function, or it have parameters.
  while (1);
}

it's ok to use if my function is a global, non-parameters function.

but when i use class member funtion(not static), i think it wont work.

So, Can you help on this if i want my function have parmaters and may be a class member function?

Aucun commentaire:

Enregistrer un commentaire