大多数情况,不需要用到binary_function!如果你在定义一个二元的functor时,几乎可以不用管这个binary_function。但是如果你使用一些function adapter的时候就需要了,这其实是在实现一种concept.
比如,定义一个functor,用来给一个vector<double> push_back一个值
比如,定义一个functor,用来给一个vector<double> push_back一个值
- struct inserter
- {
- public:
- void operator()(double n, vector<double> &v)
- {
- v.push_back(n);
- }
- };
- inserter f;
- vector<dobule> vd;
- f(1.0, vd);
现在,如果有一个算法,会往容器里追加一些值。例如这样
- template<typename Functor>
- void append(Functor f)
- {
- double x;
- while(cin>>x)
- f(x);
- }
- template<typename Functor>
- struct inserter_adapter
- {
- inserter_adapter(const Functor& f, vector<double>& v)
- :f_(f), v_(v)
- {}
- void operator()(double x)
- {
- f_(x, v_);
- }
- Functor f_;
- vector<double>& v_;
- };
那么在使用的时候就是下面这样。
- inserter f;
- vector<dobule> vd;
- inserter_adapter ia(f, vd);
- append(ia);
其实使用STL,你完全不用再写一个inserter_adapter,STL中有一个std::bind2nd的function adapter,作用和inserter_adapter一样,是把第二个参数绑定,让二元的函数对象变成一元的,就能符合只需要一个参数的算法。
但是前面定义的inserter这个函数对象不能直接用在std::bind2nd上,它还不符合std::bind2nd的concept。继承一下binary_function就搞定了。
- struct inserter
- :public std::binary_function<double, vector<double>&, void> // 分别是第一个参数,第二个参数,返回值类型
- {
- public:
- void operator()(double n, vector<double>& v)
- {
- v.push_back(n);
- }
- };
- inserter f;
- vector<dobule> vd;
- inserter_adapter ia(f, vd);
- append(std::bind2nd(f, vd)); // bind2nd帮你创建了一个binder2nd对象
struct inserter :public std::binary_function<double, vector<double>&, void> // 分别是第一个参数,第二个参数,返回值类型 { public: void operator()(double n, vector<double>& v) { v.push_back(n); } }; inserter f; vector<dobule> vd; inserter_adapter ia(f, vd); append(std::bind2nd(f, vd)); // bind2nd帮你创建了一个binder2nd对象
其实符合了bind2nd的concept,就意味着bind2nd知道了你的inserter需要什么样的参数类型,这样就可以帮你传递参数到你的inserter里面去了。