C++11 std::bind
阿新 • • 發佈:2018-11-07
一 宣告
標頭檔案<functional>
template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
template< class R, class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
引數說明:
f:A Function object, point to function or pointer to member.(函式物件,函式指標,函式引用, 指向成員函式指標或指向成員變數指標)
args: 要繫結的引數列表,每個引數可以是a value 或者 a placeholder。
作用:
bind生成 f 的轉發呼叫包裝器。呼叫該包裝器相當於一一些繫結的引數呼叫f。實現延時呼叫。
二 舉例
#include <iostream> #include <functional> struct Demo { void print (int a, int b){}; int a_; }; int add(int& a, int& b) { a++; b++; std::cout << "add " << a << " " << b << std::endl; return a + b; } int main() { using namespace std::placeholders; { int a = 1; int b = 2; auto f = std::bind(add, a, _1); // 繫結普通函式, _1與呼叫時傳入時相應位置引數對應 a = 100; f(b); // output: add 2 3 說明bind時,預定引數值已經確定 } { int a = 1; int b = 2; auto f = std::bind(add, a, _1); f(b); std::cout << " a: " << a << std::endl; // output: a: 1 std::cout << " b: " << b << std::endl; // output: b: 3 其實還是值傳遞,原因是add函式引數是引用導致 } Demo demo; auto f1 = std::bind(&Demo::print, &demo, _1, 10); // 繫結成員函式 auto f2 = std::bind(&Demo::a_, &demo); // 繫結成員變數 f1(20); // output: 20 10 1 f2() = 20; f1(20); // output: 20 10 20 system("pause"); return 0; }
三 注意
1、到 bind 的引數被複制或移動,而且決不按引用傳遞,除非用std::ref或者std::cref包裝。
2、If fn is a pointer to member, the first argument expected by the returned function is an object of the class *fn
is a member (or a reference to it, or a pointer to it).(當繫結的是成員函式或者成員變數時,第一個引數要是類例項、例項引用或者例項指標。即可以預繫結也可以佔位後,呼叫時傳遞進來)。