boost::function/bind
生活随笔
收集整理的這篇文章主要介紹了
boost::function/bind
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
boost::function/bind
boost::function
頭文件:<boost/function.hpp>
boost::function是一個函數模板,可以代替具有相同返回類型,相同參數和相同參數個數的不同函數,和函數指針有些類似,用于封裝函數,定義之后可以多次調用
// 簡單的例子 typedef boost::function<int(int ,int)> function_type;int Max(int a, int b) {return a > b ? a : b; }int main() {function_type p = &Max;int ans = p(1, 2);cout << ans << endl; // 輸出2return 0; }boost::bind
頭文件:<boost/bind.hpp>
boost::bind和boost::function結合,可以做到函數指針做不到的綁定,可以指向任何函數,包括成員函數
bind接受的第一個參數是一個可調用的對象,包括函數,函數指針,函數對象,成員函數指針,之后bind最多接受9個參數,參數量要和綁定的函數參數數量相同,bind綁定之后返回一個函數對象,內部保存了函數拷貝,具有operator(),返回類型自動為綁定的返回類型。在發生調用的時候,函數對象把之前存儲的參數轉發給函數完成調用
#include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp> using namespace std;int Max(int a, int b) {return a > b ? a : b; }int main() {boost::function<int()> f;f = boost::bind(&Max, 1, 2);cout << f() << endl; // 輸出2boost::function<int(int, int)> f1;f1 = boost::bind(&Max, _1, _2);cout << f1(1, 2) << endl; // 輸出2//int ret = boost::bind(&Max, _1, _2)(1, 2);//cout << ret << endl; // 輸出2return 0; } #include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp> using namespace std;class A { public:void fun1() {cout << "hello A" << endl;}void fun2(int a, int b, int c) {cout << a << " " << b << " " << c << endl;} };int main() {A a;boost::function<void()> f;f = boost::bind(&A::fun1, &a);f(); // 輸出 hello Af = boost::bind(&A::fun2, &a, 1, 2, 3);f(); // 輸出 1 2 3boost::function<void(int, int)> f1;f1 = boost::bind(&A::fun2, &a, _1, 2, _2);f1(1, 3); // 輸出1 2 3return 0; }總結
以上是生活随笔為你收集整理的boost::function/bind的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kali 设置中文字体
- 下一篇: __thread