I am writing my own timer in c++. I was wondering whether it is possible to pass a function to the timer constructor and call this function later.
I was thinking about using function pointers for this, however I can't find a solution for passing a non-static function inside the class itself.
G++ gives me this error:
Server.cpp:61:54: error: invalid use of non-static member function serverTimer = new timer::Timer(onTimerTick,3000);
My class Server.cpp looks like this:
private:
void onTimerTick(){
//do something with class variables, so can't use static? :(
}
public:
Server(int port) : socket(port)
{
serverTimer = new timer::Timer(onTimerTick,1000);
serverTimer->start();
}
This is timer.h:
#ifndef TIMER_H
#define TIMER_H
namespace timer {
class Timer{
public:
Timer(void (*f) (void),int interval);
std::thread* start();
void stop();
private:
int interval;
bool running;
void (*f) (void);
};
}
#endif
This is timer.cpp:
#include <thread>
#include <chrono>
#include "timer.h"
timer::Timer::Timer(void (*f) (void),int interval){
this->f = f;
this->interval = interval;
}
std::thread* timer::Timer::start(){
this->running = true;
return new std::thread([this]()
{
while(this->running){
this->f();
std::this_thread::sleep_for(std::chrono::milliseconds(this->interval));
}
});
//return
}
void timer::Timer::stop(){
this->running = false;
}
Is there a better solution for this problem, or is this the wrong syntax for passing my function? Hope someone has a great solution for this.
std::function.delegates. Just search stack overflow for c++ and delegates and you will find thousands of pages ;)std::atomic<bool> runningand returningstd::thread*is suspicious too.