您的位置:首页 > 编程语言 > C语言/C++

C++实现回调函数 funtor

2008-06-05 16:48 555 查看
在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);

}    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息