C++ Function Callbacks: Cannot convert from a member function to a function signature

后端 未结 6 515
盖世英雄少女心
盖世英雄少女心 2020-11-29 12:22

I\'m using a 3rd party library that allows me to register callbacks for certain events. The register function looks something like this. It uses the Callback signature.

6条回答
  •  清酒与你
    2020-11-29 12:56

    Due to the inflexible hardcoding of an actual function type for the callback you can't use any of the normal adapting or binding tricks to help you here. The third party library really wants you to pass in a non-member function and there isn't much you can do. You may want to consider why you're trying to pass it the address of a member function, and if your design or use of the library could change.

    One option, if you only need to set a single callback, is to have a static or namespace private function that refers to a singleton instance pointer, and uses that to dispatch upon callback.

    If you need multiple items, then possibly a template would wrap the hackiness (untested code here, just the idea).

    template 
    struct CallbackHolderHack
    {
        static int callback_func(std::string str) { dispatchee_->myCallback(str); }
        static MyStruct* dispatchee_;
    };
    
    template 
    MyStruct* CallbackHolderHack::dispatchee_(0);
    

    And use it:

    CallbackHolderHack<0>::dispatchee_ = new MyStruct;
    registerCallback(&CallbackHolderHack<0>::callback_func);
    

提交回复
热议问题