How to pass a method as callback to another class?

后端 未结 4 582
没有蜡笔的小新
没有蜡笔的小新 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 01:58

    Member functions have an implicit first parameter, a this pointer so as to know which object to call the function on. Normally, it's hidden from you, but to bind a member function to std::function, you need to explicitly provide the class type in template parameter.

    #include 
    #include 
    
    struct Callback_t {
        void myCallback(int)
        {
            std::cout << "You called me?";
        }
    };
    
    class SomeClass {
    public:
        SomeClass() : callback() { }
        typedef std::function Callback;
                               //  ^^^^^^^^^^^
    
        void registerCallback(const Callback& c)
        {
            callback = c;
        }
    
        void callOn(Callback_t* p)
        {
            callback(p, 42);
        }
    private:
        Callback callback;
    };
    
    int main()
    {
        SomeClass sc;
        sc.registerCallback(&Callback_t::myCallback);
    
        Callback_t cb; // we need an instance of Callback_t to call a member on
        sc.callOn(&cb);
    }
    

    Output: You called me?;

提交回复
热议问题