C++11之std::function和std::bind
阿新 • • 發佈:2019-01-10
std::function是可呼叫物件的包裝器,它最重要的功能是實現延時呼叫:
#include "stdafx.h" #include<iostream>// std::cout #include<functional>// std::function void func(void) { std::cout << __FUNCTION__ << std::endl; } class Foo { public: static int foo_func(int a) { std::cout << __FUNCTION__ << "(" << a << ") ->: "; return a; } }; class Bar { public: int operator() (int a) { std::cout << __FUNCTION__ << "(" << a << ") ->: "; return a; } }; int main() { // 繫結普通函式 std::function<void(void)> fr1 = func; fr1(); // 繫結類的靜態成員函式 std::function<int(int)> fr2 = Foo::foo_func; std::cout << fr2(100) << std::endl; // 繫結仿函式 Bar bar; fr2 = bar; std::cout << fr2(200) << std::endl; return 0; }
由上邊程式碼定義std::function<int(int)> fr2,那麼fr2就可以代表返回值和引數表相同的一類函式。可以看出fr2儲存了指代的函式,可以在之後的程式過程中呼叫。這種用法在實際程式設計中是很常見的。
std::bind用來將可呼叫物件與其引數一起進行繫結。繫結後可以使用std::function進行儲存,並延遲到我們需要的時候呼叫:
(1) 將可呼叫物件與其引數繫結成一個仿函式;
(2) 可繫結部分引數。
在繫結部分引數的時候,通過使用std::placeholders來決定空位引數將會是呼叫發生時的第幾個引數。
#include "stdafx.h" #include<iostream>// std::cout #include<functional>// std::function class A { public: int i_ = 0; // C++11允許非靜態(non-static)資料成員在其宣告處(在其所屬類內部)進行初始化 void output(int x, int y) { std::cout << x << "" << y << std::endl; } }; int main() { A a; // 繫結成員函式,儲存為仿函式 std::function<void(int, int)> fr = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2); // 呼叫成員函式 fr(1, 2); // 繫結成員變數 std::function<int&(void)> fr2 = std::bind(&A::i_, &a); fr2() = 100;// 對成員變數進行賦值 std::cout << a.i_ << std::endl; return 0; }