How to pass a method as callback to another class?

后端 未结 4 584
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 01:10

I have a question regarding callbacks using tr1::function. I\'ve defined the following:

  class SomeClass {
    public:
      typedef std::tr1::function

        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-26 02:00

    Use templates:

    template 
    class B
    {
      public:
        typedef void (T::*TCallBackFunction)(void);   
        void SetCallBack(T* pCallBackClass, TCallBackFunction pCallBackFunction)
        {
          if(pCallBackFunction && pCallBackClass)
          {
            m_pCallBackFunction = pCallBackFunction;
            m_pCallBackClass = pCallBackClass;
          }
        }
        void StartCallBackFunction()
        {
          (pCallBackClass->(*m_pCallBackFunction))();
        }
      private:
        TCallBackFunction m_pCallBackFunction;
        T* m_pCallBackClass;
    };
    

    Such like this. And use it:

    ...
    B b;
    b.SetCallBack(&b, &MyClass::MyFunction);
    ...
    

提交回复
热议问题