weidagang2046的專欄

          物格而后知致
          隨筆 - 8, 文章 - 409, 評論 - 101, 引用 - 0
          數據加載中……

          Use Functor for Callbacks in C++

          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
          {


          public: functor(const base& b):m_base(b) {} int operator() () { return m_base.get(); }
          private:
                   base m_base; };
          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);
          }
          

          posted on 2006-01-21 15:45 weidagang2046 閱讀(447) 評論(0)  編輯  收藏 所屬分類: C/C++

          主站蜘蛛池模板: 伊川县| 灌阳县| 宁陵县| 武宁县| 龙泉市| 廉江市| 河源市| 连云港市| 家居| 盱眙县| 双柏县| 托里县| 富裕县| 上饶市| 沙坪坝区| 濉溪县| 荥阳市| 宕昌县| 金塔县| 亳州市| 新巴尔虎右旗| 华蓥市| 蓬莱市| 宁德市| 玉屏| 弥渡县| 无锡市| 水城县| 普兰店市| 大方县| 铁岭市| 类乌齐县| 防城港市| 东阿县| 镇沅| 新建县| 兴宁市| 阿拉善盟| 河南省| 江孜县| 准格尔旗|