How to call a non static member function from a static member function without passing class instance

后端 未结 4 602
温柔的废话
温柔的废话 2020-12-16 06:36

I need to call a non static member function from a static member function of the same class. The static function is a callback. It can receive only void as data, though whic

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 07:22

    If your instance is a singleton (usually implemented using a private or protected constructor and a static pointer to itself) you can do e.g.:

    class MyClass {
    private:
      MyClass():myInstance(0) {}
    
      MyClass *myInstance;
    
      void callback();
    public:
      ~MyClass() {}
    
      static MyClass *getInstance();
    
      static void myCallback();    
    };
    
    MyClass *MyClass::getInstance() {
      if(!myInstance) {
        myInstance = new MyClass;
      }
      return myInsance;
    }    
    
    void MyClass::callback() {
     // non-static callback
    }
    
    void MyClass::myCallback() {
      getInstance()->callback();
    }
    

    If you don't use a singleton but you can pass the instance cast to a void * then you can do this instead:

    void MyClass::myCallback(void *data) {
      MyClass *instance = static_cast(data);
      instance->callback();
    }
    

提交回复
热议问题