如何使用静态 C++ 方法作为 Poco 计时器的回调? [英] How can I use a static C++ method as a callback for a Poco timer?

查看:107
本文介绍了如何使用静态 C++ 方法作为 Poco 计时器的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是我在谈论这个 Poco 类的构造函数:Poco.TimerCallback

Particularly I'm talking about the constructor of this Poco class: Poco.TimerCallback

我想在遗留的 C++ 代码中使用它,其中我编写的大多数类都是静态的",因此它们只包含静态方法而没有构造函数,只是因为无论如何我都不需要这些对象的多个实例,而这些类只是为了封装.嗯,是的,Poco 家伙建议添加这样的回调方法:

I would like to use it in legacy C++ code where most of the classes I've written are "static" so that they only contain static methods and no constructors, just because I won't need multiple instances of such objects anyway, and the classes are merely for encapsulation. Well yeah, the Poco guys suggest to add a callback method like this:

TimerCallback<MyClass> callback(*this, &MyClass::onTimer);
timer.start(callback);

我是否正确理解此代码片段:MyClass::onTimer 也可能是 MyClass 的静态方法,但我还需要 MyClass 的当前实例,这样没有被实例化的静态类的方法就被简单地禁止用作TimerCallback,还是我错了?

Do I understand this code snippet correctly: MyClass::onTimer may also be a static method of MyClass, but I also need the current instance of MyClass, so that methods of static classes, which are not instantiated, are simply banned from being used as a TimerCallback, or am I wrong?

谢谢.

推荐答案

我不会称之为禁止" - 只是没有实现函数回调,并且没有什么可以阻止您自己实现它(并将其作为贡献,如果您愿意的话).

I would not call it "banned" - the function callbacks are just not implemented, and there is nothing preventing you to implement it yourself (and send it back as a contribution, if you are inclined to do so).

我只是扩展 TimerTaskAdapter,因此它不需要对象实例,例如.像这样:

I'd just extend the TimerTaskAdapter, so that it does not require object instance, eg. something like this:

typedef void (*FunctionCallback)(TimerTask&);
TimerTaskAdapter(FunctionCallback func): _pObject(0), _method(0), _func(func){}
...
FunctionCallback _func;

然后在TimerTaskAdapter::run()中检测什么是null,是否调用方法或函数:

Then detect in TimerTaskAdapter::run() what is null and whether to call the method or function:

void run()
{
    if (_pObject) (_pObject->*_method)(*this);
    else (*_func)(*this);
}

这篇关于如何使用静态 C++ 方法作为 Poco 计时器的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆