Boost::bind

/*
Boost::bind

1) bind1st,bind2st函数绑定器,把二元函数对象变为一元函数对象。
2) mem_fun,把成员函数变为函数对象。
3) fun_ptr,把一般的全局函数变为函数对象。
4) boost::bind(),统一的接口实现以上所有的功能。

注意
1) 现在的类库最多可以支持9个参数。
2)在绑定一个成员函数时,bind 表达式的第一个参数必须是成员函数所在类的实例!理解这个规则的最容易的方法是,这个显式的参数将取替隐式的 this ,被传递给所有的非静态成员函数。细心的读者将会留意到,实际上这意味着对于成员函数的绑定器来说,只能支持八个参数,因为第一个要用于传递实际的对象。
3)当我们传递某种类型的实例给一个 bind 表达式时,它将被复制,除非我们显式地告诉 bind 不要复制它。要避免复制,我们必须告诉bind 我们想传递引用而不是它所假定的传值。我们要用 boost::ref 和 boost::cref (分别用于引用和 const 引用)来做到这一点,它们也是Boost.Bind 库的一部分。还有一种避免复制的方法;就是通过指针来传递参数而不是通过值来传递。
4) 通过 Boost.Bind, 你可以象使用非虚拟函数一样使用虚拟函数,即把它绑定到最先声明该成员函数为虚拟的基类的那个虚拟函数上。这个绑定器就可以用于所有的派生类。如果你绑定到其它派生类,你就限制了可以使用这个绑定器的类。
5)bind还可以绑定成员变量。
*/

#include "stdafx.h"
#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <algorithm>
#include "boost/bind.hpp"

using namespace std;

struct point
{
int x,y;
point(int a=0,int b=0):x(a),y(b){}
void print(){
cout << "(" << x << "," << y << ")\n";
}
void setX(int a){
cout << "setX:" << a << endl;
}
void setXY(int x,int y){
cout << "setX:" << x << ",setY:" << y << endl;
}
void setXYZ(int x,int y,int z){
cout << "setX:" << x << ",setY:" << y << "setZ:" << z << endl;
}
};


int main(void){

std::vector<int> ints;
ints.push_back(7);
ints.push_back(4);
ints.push_back(12);
ints.push_back(10);
int count=std::count_if(ints.begin(), ints.end(),
boost::bind(std::logical_and<bool>(),
boost::bind(std::greater<int>(),_1,5),
boost::bind(std::less_equal<int>(),_1,10))
);
std::cout << count << '\n';

std::vector<int>::iterator int_it=std::find_if(ints.begin(),ints.end(),
boost::bind(std::logical_and<bool>(),
boost::bind(std::greater<int>(),_1,5),
boost::bind(std::less_equal<int>(),_1,10))
);
if (int_it!=ints.end())
{ std::cout << *int_it << '\n';}


point p1,p2;
bind(&point::setX,p1,_1)(10);
bind(&point::setXY,p1,_1,_2)(10,20);
bind(&point::setXYZ,p2,_1,_2,_3)(10,20,30);
vector<point> v(2);
//for_each的时候只需要_1就可以了
for_each(v.begin(),v.end(),bind(&point::print,_1));
for_each(v.begin(),v.end(),bind(&point::setX,_1,10));
for_each(v.begin(),v.end(),bind(&point::setXY,_1,10,20));
for_each(v.begin(),v.end(),bind(&point::setXYZ,_1,10,20,30));

return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值