C++: static function wrapper that routes to member function?

前端 未结 4 336
北荒
北荒 2021-01-14 05:45

I\'ve tried all sorts of design approaches to solve this problem, but I just can\'t seem to get it right.

I need to expose some static functions to use as callback f

4条回答
  •  借酒劲吻你
    2021-01-14 06:28

    Something like the below. The singleton is in class Callback, the Instance member will return a statically allocated reference to a CallbackImpl class. This is a singleton because the reference will only be initialised once when the function is first called. Also, it must be a reference or a pointer otherwise the virtual function will not work.

    class CallbackImplBase
    {
    public:
       virtual void MyCallBackImpl() = 0;
    };
    
    class CallbackImpl : public CallbackImplBase
    {
    public:
        void MyCallBackImpl()
        {
            std::cout << "MyCallBackImpl" << std::endl;
        }
    };
    
    class Callback
    {
    public:
        static CallbackImplBase & Instance()
        {
            static CallbackImpl instance;
            return instance;
        }
    
        static void MyCallBack()
        {
            Instance().MyCallBackImpl();
        }
    };
    
    extern "C" void MyCallBack()
    {
        Callback::MyCallBack();
    }
    

提交回复
热议问题