C++ Boost::bind函数包装器使用,boost::bind与伪函数的绑定使用

       在我们使用stl的 一些算法的时候,比如find_if,for_each等,需要使用仿函数,如果仿函数有2个参数,但是算法需要一个一元的仿函数的时候,我们可以使用适配器,boost库中boost::bind就帮助我们定义了函数适配器

       下面主要讲了boost::bind如何适配函数,成员函数,Lambada函数,伪函数

        

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <boost\bind.hpp>
#include <functional>
using namespace std;

int add(int a,int b){
	cout << a + b << endl;
	return a+b;
}

struct Module{

private:
	int num;
public:
	Module(int x):num(x){
	
	}

	void test(int a ,int b){
		cout << "testmodule" << a + b << endl;
	}

	void testA(int a ,int b){
		cout << "testmodule" << a + b + num << endl;
	}
	
};


struct Student:public binary_function<int,int,void>{

	void operator()(int a, int b){
	   cout << a + b << endl;
	}

};

void main(){

   //boost::bind简单的将就是函数适配器 两个参数的函数通过bind可以变为1个参数使用
   //bind可以绑定函数 lambada 伪函数

	vector<int> myvec;
	myvec.push_back(10);
	myvec.push_back(20);
	myvec.push_back(30);

	for_each(myvec.begin(),myvec.end(),boost::bind(add,20,_1));

	//bind绑定lambada 这种情况是ERROR
	//for_each(myvec.begin(),myvec.end(), boost::bind([](int a,int b){cout << a + b << endl;},20,_1) );
	//bind绑定lambada需要使用函数包装器
	auto function = std::function<void(int,int)>([](int a,int b){cout << a + b << endl;});
	for_each(myvec.begin(),myvec.end(),boost::bind(function,22,_1));

	//boost::bind绑定成员函数
	Module testModule(100);
	for_each(myvec.begin(),myvec.end(),boost::bind(&Module::testA,&testModule,33,_1));
	
	//boost::bind绑定伪函数 Student必须继承二进制函数类
	for_each(myvec.begin(),myvec.end(),boost::bind(Student(),52,_1));

   cin.get();

}





void main2(){

	std::vector<int> myvec;
	myvec.push_back(1);
	myvec.push_back(2);
	myvec.push_back(3);

	//std::for_each(myvec.begin(),myvec.end(),[](int& data){});
	std::for_each(myvec.begin(),myvec.end(),boost::bind(add,10,_1));
	//函数包装器
	function<void(int,int)> myfunc = [](int a,int b){cout << a + b << endl;};
	std::for_each(myvec.begin(),myvec.end(),boost::bind(myfunc,20,_1));
    cin.get();
}

主要是了解函数适配器的作用,以及bind各种函数的细节

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值