天天看點

ptr_fun

頭檔案:<functional>

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

[cpp]  view plain copy print ?

  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直接綁定普通函數,則編譯出錯。

[cpp]  view plain copy print ?

  1. #include <algorithm>    
  2. #include <functional>    
  3. #include <iostream>    
  4. using namespace std;    
  5. int sum(int arg1, int arg2)    
  6. {    
  7.     std::cout<< "arg1 = " << arg1 << std::endl;    
  8.     std::cout<< "arg2 = " << arg2 << std::endl;    
  9.     int sum = arg1 + arg2;    
  10.     std::cout << "sum = " << sum << std::endl;    
  11.     return sum;    
  12. }  
  13. int main(int argc, char *argv[], char *env[])  
  14. {    
  15.     bind1st(ptr_fun(sum), 1)(2);        // the same as sum(1,2)    
  16.     bind2nd(ptr_fun(sum), 1)(2);        // the same as sum(2,1)    
  17.     return 0;  
  18. }