您的位置:首页 > 编程语言 > C语言/C++

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

2017-04-25 22:43 429 查看
       在我们使用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各种函数的细节
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: