STL中的函数配接器,是指能够将仿函数和另一个仿函数或某个值或某一个一般函数结合起来形成一个新的仿函数。
在STL中函数配接器一共有四个,分别是:
bind1nd(op ,value) 相当于构成op(value,param),即把value结合成op的第一个参数
bind2nd(op ,value)相当于构成op(param,value),即把value结合成op的第二个参数
not1(op)相当于构成!op(param),即op(param)的结果进行逻辑非运算
not2(op)相当于构成!op(param,param),即把op(param,param)的结构进行逻辑非运算
下面先以bind2nd为例示例:
- #include<iostream>
- #include<vector>
- #include<algorithm>
- #include<iterator>
- #include<functional>
- using namespace std;
-
- class A :public binary_function<int,int,void>
- {
- public:
- A(){}
- ~A(){}
- void operator()( int a, int b) const
- {
- ostream_iterator<int> os(cout,"--");
- *os = a + b;
- }
- private:
- };
-
- void fun(int a,int b)
- {
- ostream_iterator<int> os(cout,"--");
- *os = a + b;
- }
-
- int Get(int a)
- {
- return a;
- }
- int main()
- {
- vector<int> B;
- for(int i = 0;i<5;i++) B.push_back(i);
-
- for_each(B.begin(), B.end(), bind2nd(A(),2));
- cout<<endl;
-
- for_each(B.begin(), B.end(), bind2nd(ptr_fun(fun),1));
- cout<<endl;
-
- for_each(B.begin(), B.end(), bind2nd(A(),Get(3)));
- }
注意在使用中注意一下几点:
一、在自己编写适用于bind2nd或bind1nd的仿函数时,该仿函数类必须继承于类binary_function(T(第一个参数类型),T(第二个参数类型),T(返回值类型))。
二、对于普通函数也需要用函数配接器结合时,需要先用ptr_fun()封装(对于ptr_fun的讲解在http://blog.csdn.net/yyc1023/article/details/38498325)。
至于其他的几个配接器的用法类似即可。
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<_Arg1, _Arg2, _Result,
- _Result (__clrcall *)(_Arg1, _Arg2)>(_Left));
- }
下面的例子就是说明了使用ptr_fun将普通函数(两个参数, 如果有多个参数, 要改用boost::bind)适配成bind1st或bind2nd能够使用的functor,否则对bind1st或bind2nd直接绑定普通函数,则编译出错。
- #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);
- bind2nd(ptr_fun(sum), 1)(2);
-
- return 0;
- }