从binary_function类继承的作用
来源:互联网 发布:淘宝购物券怎么用 编辑:程序博客网 时间:2024/04/30 05:11
大多数情况,不需要用到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里面去了。
- 从binary_function类继承的作用
- 从binary_function类继承的作用
- binary_function
- binary_function的用处(转)
- 为什么在定义能够使用函数适配器的函数的时候要继承一下std::unary_function或者std::binary_function
- stl 中 std::binary_function 的使用
- stl中std::binary_function的使用
- struts2的继承ActionSuport类的作用
- 继承情况下的类作用域
- 多重继承下的类作用域
- struts2中继承ActionSupport类的作用
- 继承情况下类的作用域
- 私有继承的作用
- 从本质认识JavaScript的原型继承和类继承
- 类从结构继承的一个问题
- 从MFC类继承的基本方式
- 访问从基类继承的成员
- C++虚继承的作用
- Tuning the buffer cache
- CB: ModalResult属性设置为mrNone,TBitBtn点击后可以不结束窗体
- R12.0.X APPS Clone 3% 和 R12.1.X 0% 过不去,等待很长时间然后报错:RC-50004
- Ubuntu上nfs的安装配置
- 在Linux中创建静态库和动态库
- 从binary_function类继承的作用
- UIManager可设置的各种属性
- [源]看看“凡客体”是什么体!
- 如何摆脱泥头车
- Java中判断两个字符串相等的两种方式
- Google手机地图体验
- 讲讲volatile的作用
- 雨中行车
- Popupwindow遇到的问题