【问题标题】:C++ non-static function pointer inside own class自己的类中的C ++非静态函数指针
【发布时间】:2016-03-07 22:09:12
【问题描述】:

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

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

G++ 给了我这个错误:

Server.cpp:61:54:错误:非静态成员函数的使用无效 serverTimer = 新计时器::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;
}

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

【问题讨论】:

  • 查找std::function
  • 您需要的是delegates。只需搜索 c++ 和委托的堆栈溢出,您就会发现数千页;)
  • @BitTickler,delegate 是一个可怕的词,它来自于禁止 pointer 的语言,所以不能使用普通的“函数指针”。
  • 注意你应该使用std::atomic&lt;bool&gt; running,返回std::thread*也是可疑的。
  • @SergeyA 语言很有趣,不是吗? C++ 上下文中的术语委托具有特殊含义。它不仅仅是“函数指针”。因此,如果它用于其他含义的其他上下文中,那么它在 c++ 上下文中的使用方式并不适用。

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


【解决方案1】:

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

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

所以你的函数指针变成:

std::function<void (void)>;

你可以这样称呼它:

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

【讨论】:

  • 太快了!它有效:) lambda 是 [this]{onTimerTick();}
  • 在简单的情况下,我个人更喜欢std::bind
  • 注意:当你的类有一个 std::function 对象,它嵌入了一个指向自身的 this 指针时,最好使该类不可复制,因为复制语义不正确。
猜你喜欢
  • 2011-11-21
  • 1970-01-01
  • 2010-11-02
  • 2018-01-02
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多