|
近日因些可悲的原因 無奈在看c# 看到其中 所謂的 委託 立刻 想起來 boost::function 然 和 function 比起來 委託 除了 有個 沒什麼意思的 異步調用外 簡直沒點意思
boost::function 是對一個 functor 的包裝(內部 保存期 副本) 讓使用者 可以 延遲 調用 functor
boost::bind 是一個 強大的 函數適配器 可以 將 functor 包裝成其他簽名形式的 boost::function
boost::function
boost::function 接受一個 模板參數 指定 函數簽名 以及一個 符合 簽名的 函數 進行 構造
同時 boost::function 重載了 operator() 可以像 一般 functor一樣 調用 function
- #include <boost/function.hpp>
- void show()
- {
- puts("cerberus it's an idea");
- }
- int show_sum(int l,int r)
- {
- int sum = l + r;
- printf("%d+%d=%d\n",l,r,sum);
- return sum;
- }
- void swap(int& l,int& r)
- {
- int tmp = l;
- l = r;
- r = tmp;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- boost::function<void()> func(show);
- func();
- boost::function<void(int,int)> func_sum(show_sum);
- func_sum(1,2);
- boost::function<void(int&,int&)> func_swap(swap);
- int l = 3;
- int r = 4;
- func_swap(l,r);
-
- printf("l=%d r=%d\n",l,r);
- return 0;
- }
复制代码
boost::bind
單獨 使用 boost::function 其不過是可能 比使用 函數指針 看起多些函數信息罷了
而且 對於c/c++這種 追求效率的語言來說 是在增加 函數調用 成本 (雖然成本很小)
然一般 都是 將 boost::function 和 boost::bind 配合 使用 boost::bind 可以將 一個簽名的 函數調用 適配到 其他簽名形式
想像下 你不需要寫 多餘的代碼 只需要 調用 bind 返回一個 適配的 function 之後 就可以直接 使用 新的 接口 操作原有接口
對於 不同 c++ 開源庫 提供的 不同風格 api 現在 你可以 輕易的 適配到 適合你的 項目
而且 這意味着 使用 boost::function 作為 接口 你可以 很容易的 為接口調用 添加 新的調用信息 而保證 和以前的 有同樣的 簽名
bind 接受 一個 函數定義 以及 最多9個 調用 參數
調用 bind 時 可以使用 _1 _2 ... _9 9個佔位符 代表 原 functor 需要的 參數 這些佔位符 將在 調用 返回的 boost::function 時 進行 傳入
- #include<boost/bind.hpp>
- class Test
- {
- public:
- Test()
- {
- value = 0;
- }
- int value;
- void add(const int a,const int b)
- {
- value = a + b;
- std::cout<<value<<std::endl;
- }
- typedef int result_type;
- result_type operator()(const int a,const int b)
- {
- return a + b;
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- //綁定普通函數 函數指針
- boost::bind(puts,"bind")
- (); //operator () 引發真實的 調用
- //使用佔位符
- boost::bind(puts,_1)
- ("bind _1"); //佔位符 以便在 () 時才傳入參數
- boost::bind(puts,_2)
- ("第一個參數被忽略","bind _2");
- //綁定成員函數
- Test t;
- boost::bind(&Test::add,
- t, //此處 會 創建 新的clas 並創建其副本 調用 add 函數 如果需要調用當前實例的 add 需要傳入指針 &t
- _1,_2)
- (10,20);
- //綁定成員變量
- t.value = 1;
- std::cout<<boost::bind(&Test::value,&t)()<<"\n";
- //綁定函數對象
- //若未定義 result_type 需要 在模板傳入 返回值型別 bind<int<(Test(),1,2)
- std::cout<<boost::bind(Test(),1,2)()<<"\n";
-
- std::system("pause");
- return 0;
- }
复制代码 |
上一篇: boost 中文翻译包,来源于google翻译组的分享下一篇: VC实现Win7任务栏编程
|