如何定义一般成员函数指针 [英] How to define a general member function pointer

查看:95
本文介绍了如何定义一般成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Timer类,当定时器到期时,必须调用一个回调方法。目前我使用正常的函数指针(它们被声明为void(*)(void),当Elapsed事件发生时调用函数指针。

I have created a Timer class that must call a callback method when the timer has expired. Currently I have it working with normal function pointers (they are declared as void (*)(void), when the Elapsed event happens the function pointer is called.

对于同样具有签名void(AnyClass :: *)(void)的成员函数也做同样的事情?

Is possible to do the same thing with a member function that has also the signature void (AnyClass::*)(void)?

感谢伙伴。

编辑:这个代码必须在Windows和实时操作系统(VxWorks)上工作,所以不要使用外部库。

This code has to work on Windows and also on a real-time OS (VxWorks) so not using external libraries would be great.

EDIT2:只是为了确保,我需要一个Timer类,在构造函数的AnyClass.AnyMethod没有参数和返回void的参数,我必须存储这个参数和后面的点

Just to be sure, what I need is to have a Timer class that take an argument at the Constructor of tipe "AnyClass.AnyMethod" without arguments and returning void. I have to store this argument and latter in a point of the code just execute the method pointed by this variable. Hope is clear.

推荐答案

依赖关系,依赖关系...确定提升但是,调用成员函数的语法是邪恶的,所以一点模板魔法可以帮助:

Dependencies, dependencies... yeah, sure boost is nice, so is mem_fn, but you don't need them. However, the syntax of calling member functions is evil, so a little template magic helps:

   class Callback
   {
   public:
      void operator()() { call(); };
      virtual void call() = 0;
   };

   class BasicCallback : public Callback
   {
      // pointer to member function
      void (*function)(void);
   public:
      BasicCallback(void(*_function)(void))
          : function( _function ) { };
      virtual void call()
      { 
          (*function)();
      };
   };   

   template <class AnyClass> 
   class ClassCallback : public Callback
   {
      // pointer to member function
      void (AnyClass::*function)(void);
      // pointer to object
      AnyClass* object;        
   public:
      ClassCallback(AnyClass* _object, void(AnyClass::*_function)(void))
          : object( _object ), function( _function ) { };
      virtual void call()
      { 
          (*object.*function)();
      };
   };

现在你可以使用Callback作为回调存储机制,因此:

Now you can just use Callback as a callback storing mechanism so:

void set_callback( Callback* callback );
set_callback( new ClassCallback<MyClass>( my_class, &MyClass::timer ) );

Callback* callback = new ClassCallback<MyClass>( my_class, &MyClass::timer ) );

(*callback)();
// or...
callback->call();

这篇关于如何定义一般成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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