How to define a general member function pointer

前端 未结 5 922
南方客
南方客 2021-02-14 21:35

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 (

5条回答
  •  抹茶落季
    2021-02-14 21:55

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

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

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

    And

    Callback* callback = new ClassCallback( my_class, &MyClass::timer ) );
    
    (*callback)();
    // or...
    callback->call();
    

提交回复
热议问题