boost bind的使用方法

2021-07-24 13:31:43 字數 2044 閱讀 7424

標頭檔案: boost/bind.hpp

bind 是一組過載的函式模板。用來向乙個函式(或函式物件)繫結某些引數。bind的返回值是乙個函式物件.

它的原始檔太長了. 看不下去. 這裡只記下它的用法:

假如有函式 fun() 如下:

voidfun(int x, int y) f;

繫結的時候可能要指出返回值的型別:

boost::bind(f, 3)();  //指出返回值的型別 void

假如有:

struct a {

void func(int x, int y) {

cout << x << "," << y << endl;

aa; 

a*pa = new a; //指標

boost::shared_ptrptr_a(pa);  //智慧型指標.

現在要向像 a::func 這樣的非靜態成員函式繫結.

若a::func有n個引數, 則 bind 要有 n+2 個引數: 指向成員函式fun的指標, 繫結到this的物件, n個引數.如:

boost::bind(&a::func, a, 3, 4)();    //輸出 3, 4

boost::bind(&a::func, pa, 3, 4)();   //輸出 3, 4

boost::bind(&a::func, ptr_a, 3, 4)();//輸出 3, 4

同樣可以用 _1 這樣的佔位符. 如:

boost::bind(&a::func, _1, 3, 4)(ptr_a);//輸出 3, 4

可以看出. 不論傳遞給bind 的第2個引數是物件. 物件指標. 還是智慧型指標. bind函式都能夠正常工作.

有個類如下. 記錄人的資訊:

class personal_info {

string name_;

intage_;

public:

intget_age();

string name();

vectorvec;

現在要對 vec 排序. 可以用 bind 函式做乙個比較謂詞

std::sort( 

vec.begin(), 

vec.end(), 

boost::bind(

std::less(),   

boost::bind(&personal_info::age,_1),     //_1 佔位符是 sort 中呼叫比較函式時的第乙個引數.

boost::bind(&personal_info::age,_2)));   //_2 佔位符是 sort 中呼叫比較函式時的第二個引數.

假如有:

vectorints;

想用 std::count_if() 來求ints中有多少是 >5 且 <=10 的. 這在常規**中通常就要寫乙個函式來實現這個謂詞:

if(i>5 && i<=10) ...

現在用 bind則可以:

std::count_if( 

ints.begin(),  ints.end(), 

boost::bind(   

std::logical_and(),   

boost::bind(std::greater(),_1,5),   

boost::bind(std::less_equal(),_1,10)));

有:mapmy_map;

my_map[0]="boost";my_map[1]="bind";

現在要輸出所有元素的 second 成員. 也就是輸出這些字串. 其中的列印函式如下:

voidprint_string(const string& s) { 

std::cout << s << '\n';

則可以:

for_each( 

my_map.begin(), 

my_map.end(), 

boost::bind(

&print_string,

boost::bind(&std::map::value_type::second,_1)

boost bind的使用方法

此文 bind boost 標頭檔案 boost bind.hpp bind 是一組過載的函式模板.用來向乙個函式 或函式物件 繫結某些引數.bind的返回值是乙個函式物件.它的原始檔太長了.看不下去.這裡只記下它的用法 9.1 對於普通函式 假如有函式 fun 如下 void fun int x,...

boost bind的使用方法

bind boost 標頭檔案 boost bind.hpp bind 是一組過載的函式模板.用來向乙個函式 或函式物件 繫結某些引數.bind的返回值是乙個函式物件.它的原始檔太長了.看不下去.這裡只記下它的用法 9.1 對於普通函式 假如有函式 fun 如下 void fun int x,int...

boost bind的使用方法

bind boost 標頭檔案 boost bind.hpp bind 是一組過載的函式模板.用來向乙個函式 或函式物件 繫結某些引數.bind的返回值是乙個函式物件.它的原始檔太長了.看不下去.這裡只記下它的用法 9.1 對於普通函式 假如有函式 fun 如下 void fun int x,int...