0

Im using C++ to create a timer. Ive look up the internet but not find anything that i can understand.Here is my code:

struct Timer{
  bool timerRunning;
  int time;
  void Timer_Service(void* param){
    timerRunning = true;
    time = 0;
      while(timerRunning){
        wait(10);
        time += 10;
      }
  }
  void startTimer(){
    Timer_Service((void*)"PROS");
    pros::Task timerservice(Timer_Service,(void*)"PROS");// <- error here "reference to non-static member function must be called"
  }
  void stopTimer(){
    timerRunning = false;
  }
  int getTime(){
    return time;
  }
};

How do i solve this error? BTW pros::Task timerservice(Timer_Service,(void*)"PROS"); is a function that initializes a multitask loop. Thanks all for your kind help.

Eden Cheung
  • 173
  • 7

1 Answers1

4

The pros::Task constructor takes a function pointer.

Function pointers and pointers-to-member-functions are not the same thing.

You will have to pass a pointer to a non-member function (or a static member), ideally a forwarding delegate. You can create a class that contains a Timer_Service*, and pass it through the void* argument. In fact, in this case, since you only need to pass the object pointer, there's no need for a wrapping class.

struct Timer
{
  bool timerRunning;
  int time;

  static void Timer_Service_Delegate(void* param) {
     Timer* ptr = reinterpret_cast<Timer*>(param);
     ptr->Timer_Service();
  }

  void Timer_Service() {
    timerRunning = true;
    time = 0;
      while(timerRunning){
        wait(10);
        time += 10;
      }
  }

  void startTimer() {
    pros::Task timerservice(
       Timer_Service_Delegate,
       reinterpret_cast<void*>(this)
    );
  }

  void stopTimer() {
    timerRunning = false;
  }

  int getTime() {
    return time;
  }
};

I suspect you'll also need to keep the pros::Task in scope, but I don't know enough about the library to train you on that. Refer to its documentation.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989