【发布时间】: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<bool> running,返回std::thread*也是可疑的。 -
@SergeyA 语言很有趣,不是吗? C++ 上下文中的术语委托具有特殊含义。它不仅仅是“函数指针”。因此,如果它用于其他含义的其他上下文中,那么它在 c++ 上下文中的使用方式并不适用。
标签: c++ c++11 timer static function-pointers