C++实现回调函数 funtor

在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);

}    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值