ptr_fun学习笔记

时间:2023-03-10 04:41:34
ptr_fun学习笔记

ptr_fun是将一个普通的函数适配成一个functor,添加上argument type和result type等类型, 其实现如下(例子里面是binary_function,unary_function同理):

  1. template<class _Arg1,
  2. class _Arg2,
  3. class _Result> inline
  4. pointer_to_binary_function<_Arg1, _Arg2, _Result,
  5. _Result(__fastcall *)(_Arg1, _Arg2)>
  6. ptr_fun(_Result (__fastcall *_Left)(_Arg1, _Arg2))
  7. {   // return pointer_to_binary_function functor adapter
  8. return (std::pointer_to_binary_function<_Arg1, _Arg2, _Result,
  9. _Result (__fastcall *)(_Arg1, _Arg2)>(_Left));
  10. }

由上面的代码可见,ptr_fun只是将一个普通的函数(或者函数指针)适配成类pointer_to_binary_function,而该类实际上是binary_function的子类,这样出来的functor就有利于同STL的算法等适配。 
下面的例子就是说明了使用ptr_fun将普通的函数适配成bind1st或bind2nd能够使用的functor,否则对bind1st或bind2nd直接绑定普通函数,则编译出错。

    1. #include <algorithm>
    2. #include <functional>
    3. #include <iostream>
    4. using namespace std;
    5. int sum(int arg1, int arg2)
    6. {
    7. cout<<"ARG 1: "<<arg1<<endl;
    8. cout<<"ARG 2: "<<arg2<<endl;
    9. int sum = arg1 + arg2;
    10. cout<<"SUM: "<<sum<<endl;
    11. return sum;
    12. }
    13. int main(int argc,char* argv[])
    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. getchar();
    18. return 0;
    19. }