头文件:<functional>
ptr_fun是将一个普通的函数适配成一个仿函数(functor), 添加上argument_type和result type等类型,它的定义如下:
- template<class _Arg1,
- class _Arg2,
- class _Result> inline
- pointer_to_binary_function<_Arg1, _Arg2, _Result,
- _Result(__clrcall *)(_Arg1, _Arg2)>
- ptr_fun(_Result (__clrcall *_Left)(_Arg1, _Arg2))
- { // return pointer_to_binary_function functor adapter
- return (pointer_to_binary_function<_Arg1, _Arg2, _Result,
- _Result (__clrcall *)(_Arg1, _Arg2)>(_Left));
- }
- #include <algorithm>
- #include <functional>
- #include <iostream>
- using namespace std;
- int sum(int arg1, int arg2)
- {
- std::cout<< "arg1 = " << arg1 << std::endl;
- std::cout<< "arg2 = " << arg2 << std::endl;
- int sum = arg1 + arg2;
- std::cout << "sum = " << sum << std::endl;
- return sum;
- }
- int main(int argc, char *argv[], char *env[])
- {
- bind1st(ptr_fun(sum), 1)(2); // the same as sum(1,2)
- bind2nd(ptr_fun(sum), 1)(2); // the same as sum(2,1)
- return 0;
- }