boost::bind与boost::function的使用

功能:

 boost::bind  绑定一个函数及其参数.

boost::function  是类和模板的组合,它定义的对象可以指向一个函数(包装一个函数 ),类似一个函数指针。既可以直接指向一个函数也可以接收bind的返回值。

返回值:

bind返回一个函数对象。

function本身是一种类模板,可被看作声明的关键字。

基本用法:

#include <boost\function.hpp>
#include <boost\bind.hpp>
#include<iostream>
using std::cout;
typedef boost::function<int(int ,int)> Func;
  
int test(int num_2,int num_2)
  {
     return num_1>num_2 ? num_1 : num_2;
  }
  
 int main()
 {
///bind////
cout<<boost::bind(test, 6,5)();

///function//
   Func f;
   f=&test;  
   f(1,'A');

///bind & function////
   Func f = boost::bind(test,_1,_2);
   cout<<f(6,5);
   return 0;
 }

[1]全参数绑定

bind(print, 3, 4)();

[2]部分参数绑定

bind( print, 3, _1)(4);//使用占位符给调用函数传参占个位置:传入4

[3]所有参数都不绑定

bind(print, _1, _2)(3, 4);

[4]bind应用于成员函数

Myfun f;

boost::bind(&Myfun::print,f, 3, 4)();

输出3       4

猜你喜欢

转载自blog.csdn.net/weixin_39953289/article/details/81389238