C++实现回调函数 funtor

来源:互联网 发布:哈工大 人工智能 教授 编辑:程序博客网 时间:2024/06/05 12:47

在C语言中,使用函数指针很容易实现回调函数,回调函数把调用者和被调用者在代码中分开。而在C++中,如果想用函数指针调用一个实例的非static方法没那么容易,因为实际上在调用对象的非静态方法时,编译器会把this指针加入该方法的参数列表了。 C++中实现回调函数可以使用funtor的方法。以下是转自http://www.devx.com/tips/Tip/27126  

Use Functor for Callbacks in C++

Using the callback function in C is pretty straightforward, but in C++ it becomes little tricky. If you want to use a member function as a callback function, then the member function needs to be associated with an object of the class before it can be called. In this case, you can use functor. Suppose you need to use the member function get() of the class base as a callback function

  class base   {

      public:        int get ()        { return 7;}

  };

 Then, you need to define a functor:  

  class CallbackFunctor {       

    functor(const base& b):m_base(b)   {}       

    int operator() () {              

        return m_base.get();       

    }

};

 Now you can use an object of CallbackFunctor as a callback function as follows. Define the function that needs a callback to take an argument of type CallbackFunctor:  

void call (CallbackFunctor& f) {       

     cout << f() << endl;

}    

int main () {    

    base b;       

    functor f(b);       

    call(f);

}    

原创粉丝点击