C std bind用法詳解

2022-09-24 13:06:12 字數 1765 閱讀 9187

c++11dwcfj中提供了std::bind。bind()函式的意義就像它的函式名一樣,是用來繫結函式呼叫的某些引數的。

bind的思想實際上是一種延遲計算的思想,將可呼叫物件儲存起來,然後在需要的時候再呼叫。而且這種繫結是非常靈活的,不論是普通函式、函式物件、還是成員函式都可以繫結,而且其引數可以支援佔位符,比如你可以這樣繫結乙個二元函式:

auto f = bind(&func, std::placeholders::_1, std::placeholders::_2);呼叫的時候通過f(1,2)實現呼叫。所以,我們可簡單的認為std::bind就是std::bind1st和std::bind2nd的加強版。

std::bind函式有兩種函式原型,定義如下:

template< class f, class... args >

/*unspecified*/ bind( f&& f, args&&... args );

template< class r, class f, class... args >

/*unspecified*/ bind( f&& f, args&&... args );

parametersf-

callable object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments

args

-list of arguments to bind, with the unbound arguments replaced by the placeholders_1, _2, _3...of namespacestd::placeholders

這裡要先學習仿函式。請參考仿函式的使用

例項1#include

#include

using namespace std;

int testfunc(int a, char c, float f)

int main()

上面這段**主要說的是bind中std::place程式設計客棧holders的使用。 std::placeholders是乙個佔位符。當使用bind生成乙個新的可呼叫物件時,std::placeholders表示新的可呼叫物件的第 幾個引數和原函式的第幾個引數進行匹配。

auto bindfunc3 = bind(testfunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);

bindfunc3(100.1, 30, 'c');

可以看到,在bind的時候,第乙個位置是testfunc,除了這個,引數的第乙個位置為佔位符std::placeholders::_2,這就表示,呼叫bindfunc3的時候,它的第二個引數——即30,和testfunc的第乙個引數匹配,所以std::placeholders::_2為30,以此類推,最後,實際執行的是testfunc(30,'c', 100.1)。 

例項2#include

#include

#include

#include

void f(int n1, int n2, int n3, const int& n4, int n5)

int g(int n1)

struct foo

int data = 10;};

int main()

參考:

c std bind 詳解及引數解析

bind std function.cpp 定義控制台應用程式的入口點。include stdafx.h include include include include 學習bind的用法 void f int n1,int n2,int n3,const int n4,int n5 int g i...

const用法詳解

物件導向是c 的重要特性.但是c 在c的基礎上新增加的幾點優化也是很耀眼的 就const直接可以取代c中的 define 以下幾點很重要,學不好後果也也很嚴重 1.const常量,如const int max 100 優點 const常量有資料型別,而巨集常量沒有資料型別。編譯器可以對前者進行型別安...

const 用法詳解

物件導向是c 的重要特性.但是c 在c的基礎上新增加的幾點優化也是很耀眼的 就const直接可以取代c中的 define 以下幾點很重要,學不好後果也也很嚴重 1.const常量,如const int max 100 優點 const常量有資料型別,而巨集常量沒有資料型別。編譯器可以對前者進行型別安...