How to define a general member function pointer

前端 未结 5 1059
南方客
南方客 2021-02-14 21:35

I have created a Timer class that must call a callback method when the timer has expired. Currently I have it working with normal function pointers (they are declared as void (

5条回答
  •  故里飘歌
    2021-02-14 21:56

    The best solution I have used for that same purpose was boost::signal or boost::function libraries (depending on whether you want a single callback or many of them), and boost::bind to actually register the callbacks.

    class X {
    public:
       void callback() {}
       void with_parameter( std::string const & x ) {}
    };
    int main()
    {
       X x1, x2;
       boost::function< void () > callback1;
    
       callback1 = boost::bind( &X::callback, &x1 );
       callback1(); // will call x1.callback()
    
       boost::signal< void () > multiple_callbacks;
       multiple_callbacks.connect( boost::bind( &X::callback, &x1 ) );
       multiple_callbacks.connect( boost::bind( &X::callback, &x2 ) );
       // even inject parameters:
       multiple_callbacks.connect( boost::bind( &X::with_parameter, &x1, "Hi" ) );
    
       multiple_callbacks(); // will call x1.callback(), x2.callback and x1.with_parameter("Hi") in turn
    }
    

提交回复
热议问题