啥也不說,直接看代碼:ios
#include <boost/bind.hpp> #include <boost/function.hpp> #include <iostream> using namespace boost; using namespace std; int f(int a, int b) { return a + b; } int g(int a, int b, int c) { return a + b * c; } class Point { public: Point(int x, int y) : _x(x), _y(y) {} void print(const char *msg) { cout << msg << "x=" << _x << ", y=" << _y << endl; } private: int _x, _y; }; int main() { //! f 有多少個參數,f 後面就要跟多少個參數。若是不明確的,用佔位符 cout << bind(f, 2, 3)() << endl; // ==> f(2, 3) cout << bind(f, 12, _1) (5) << endl; // ==> f(12, 5),其中參數b爲不明確參數 cout << bind(g, _2, _1, 3) (3, 5) << endl; // ==> g(5, 3, 3) 注意順序 Point p(11, 34); Point &rp = p; Point *pp = &p; bind(&Point::print, p, "Point: ") (); // ^ ^ // 注意,爲表示Point::print爲成員函數,成員函數前面要加&區分。 // 對象能夠爲實例、引用、指針 bind(&Point::print, rp, "Reference: ") (); //! 引用 bind(&Point::print, pp, _1) ("Pointer: "); //! 指針 bind(&Point::print, _1, _2) (p, "As parameter: "); //! 對象也能夠用佔位符暫時代替 //! function的類型定義與須要的參數有關 function<void ()> func0 = bind(&Point::print, p, "func0: "); function<void (const char *)> func1 = bind(&Point::print, pp, _1); func0(); //! function對象的調用 func1("func1: "); return 0; }
通常狀況下,bind 與 function 配合使用。函數
bind與function還能夠將類型完成不一樣的函數(成員函數與非成員函數)包裝成統一的函數調用接口。以下示例:
spa
#include <boost/bind.hpp> #include <boost/function.hpp> #include <iostream> #include <vector> using namespace boost; using namespace std; class Point { public: Point(int x, int y) : _x(x), _y(y) {} void print(string msg) { cout << msg << "x=" << _x << ", y=" << _y << endl; } private: int _x, _y; }; class Person { public: Person(string name, int age) : _name(name), _age(age) {} void sayHello() { cout << "Hello, my name is " << _name << ", my age is : " << _age << endl; } private: string _name; int _age; }; void printSum(int limit) { int sum = 0; for (int i = 0; i < limit; ++i) { sum += i; } cout << "sum = " << sum << endl; } void doAll(vector<function<void ()> > &funcs) { for (size_t i = 0; i < funcs.size(); ++i) { funcs[i] (); } } int main() { vector<function<void ()> > funcList; Person john("John", 23); funcList.push_back(bind(&Person::sayHello, john)); Point p1(23, 19); funcList.push_back(bind(&Point::print, p1, "Point: ")); funcList.push_back(bind(printSum, 20)); doAll(funcList); return 0; }