ptr_fun

頭文件:<functional>

ptr_fun是將一個普通的函數適配成一個仿函數(functor), 添加上argument_type和result type等類型,它的定義如下:

  1. template<class _Arg1,  
  2.     class _Arg2,  
  3.     class _Result> inline  
  4.     pointer_to_binary_function<_Arg1, _Arg2, _Result,  
  5.         _Result(__clrcall *)(_Arg1, _Arg2)>  
  6.             ptr_fun(_Result (__clrcall *_Left)(_Arg1, _Arg2))  
  7.     {    // return pointer_to_binary_function functor adapter  
  8.     return (pointer_to_binary_function<_Arg1, _Arg2, _Result,  
  9.         _Result (__clrcall *)(_Arg1, _Arg2)>(_Left));  
  10.     }  
下面的例子就是說明了使用ptr_fun將普通函數(兩個參數, 如果有多個參數, 要改用boost::bind)適配成bind1st或bind2nd能夠使用的functor,否則對bind1st或bind2nd直接綁定普通函數,則編譯出錯。
  1. #include <algorithm>    
  2. #include <functional>    
  3. #include <iostream>    
  4.   
  5. using namespace std;    
  6.   
  7. int sum(int arg1, int arg2)    
  8. {    
  9.     std::cout<< "arg1 = " << arg1 << std::endl;    
  10.     std::cout<< "arg2 = " << arg2 << std::endl;    
  11.   
  12.     int sum = arg1 + arg2;    
  13.     std::cout << "sum = " << sum << std::endl;    
  14.   
  15.     return sum;    
  16. }  
  17.   
  18. int main(int argc, char *argv[], char *env[])  
  19. {    
  20.     bind1st(ptr_fun(sum), 1)(2);        // the same as sum(1,2)    
  21.     bind2nd(ptr_fun(sum), 1)(2);        // the same as sum(2,1)    
  22.   
  23.     return 0;  
  24. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章