C ++非静态函数指针在自己的类

时间:2016-03-07 22:09:12

标签: c++ c++11 timer static function-pointers

我在c ++中编写自己的计时器。我想知道是否可以将函数传递给计时器构造函数并稍后调用此函数。

我正在考虑为此使用函数指针,但是我找不到在类本身内部传递非静态函数的解决方案。

G ++给了我这个错误:

  

Server.cpp:61:54:错误:无效使用非静态成员函数          serverTimer = new timer :: Timer(onTimerTick,3000);

我的类Server.cpp如下所示:

    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();
      }

这是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

这是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;
}

这个问题是否有更好的解决方案,或者这是传递我的函数的错误语法? 希望有人有一个很好的解决方案。

1 个答案:

答案 0 :(得分:3)

问题是你为独立函数指定了一个函数指针,但是你试图将它绑定到一个成员函数。 (非静态)成员函数确实不同:它们有一个隐藏的this指针需要传递给它们。

要解决这个问题,一种解决方案是使用std :: function而不是函数指针,然后将必要的代码作为lambda传递。

所以你的函数指针变为:

std::function<void (void)>;

你可以这样称呼它:

serverTimer = new timer::Timer([this]{onTimerTick ();},1000);
相关问题