[C++11]可调用对象绑定器
生活随笔
收集整理的這篇文章主要介紹了
[C++11]可调用对象绑定器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
std::bind用來將可調(diào)用對象與其參數(shù)一起進行綁定。綁定后的結(jié)果可以使用std::function進行保存,并延遲調(diào)用到任何我們需要的時候。通俗來說,它主要有兩個作用:
1.將可調(diào)用對象與其參數(shù)一起綁定成一個仿函數(shù)。
2.將多元(參數(shù)個數(shù)為n,n > 1)可調(diào)用對象轉(zhuǎn)換為一元或者(n -1)元可調(diào)用對象,即只綁定部分參數(shù)。
綁定器函數(shù)使用語法格式如下:
//綁定非類成員函數(shù)/變量 auto f = std::bind(可調(diào)用對象地址,綁定的參數(shù) / 占位符); //綁定類成員函數(shù)/變量 auto f = std::bind(類函數(shù) / 成員地址,類實例對象地址,綁定的參數(shù) / 占位符);代碼如下:
#include <iostream> #include <functional> using namespace std;void output(int x, int y) {cout << x << " " << y << endl; }int main() {bind(output, 1, 2)();bind(output, placeholders::_1, 2)(10);bind(output, 2, placeholders::_1)(10);//bind(output, 2, placeholders::_2)(10);//error,調(diào)用時沒有第二個參數(shù)bind(output, 2, placeholders::_2)(10, 20);bind(output, placeholders::_1, placeholders::_2)(10, 20);bind(output, placeholders::_2, placeholders::_1)(10, 20);return 0; }測試結(jié)果:
可調(diào)用對象綁定器的使用:
代碼如下:
#include <iostream> #include <functional> using namespace std;void testFunc(int x, int y, const function<void(int, int)> &f) {if (x % 2 == 0){f(x, y);} }void output_add(int x, int y) {cout << "x = " << x << ", y = " << y << ",x+y = " << x + y << endl; }int main() {for (int i = 0; i < 10; i++){auto f = bind(output_add, i + 100, i + 200);testFunc(i, i, f);auto f1 = bind(output_add, placeholders::_1, placeholders::_2);testFunc(i, i, f1);}return 0; }測試結(jié)果:
代碼如下:
#include <iostream> #include <functional> using namespace std;class Test { public:void output(int x, int y){cout << "x = " << x << " " << "y = " << y << endl;}int m_number = 100; };int main() {//成員函數(shù)綁定Test t;auto f2 = bind(&Test::output, &t, 520, placeholders::_1);f2(1314);//成員變量綁定auto f3 = bind(&Test::m_number, &t);cout << f3() << endl;f3() = 666;cout << f3() << endl;return 0; }測試結(jié)果:
可調(diào)用對象包裝器的使用:
代碼如下:
#include <iostream> #include <functional> using namespace std;class Test { public:void output(int x, int y){cout << "x = " << x << " " << "y = " << y << endl;}int m_number = 100; };int main() {//成員函數(shù)綁定Test t;auto f2 = bind(&Test::output, &t, 520, placeholders::_1);f2(1314);function<void (int,int)> f22 = bind(&Test::output, &t, 520, placeholders::_1);//成員變量綁定auto f3 = bind(&Test::m_number, &t);function<int&(void )> f33= bind(&Test::m_number, &t);cout << f3() << endl;f3() = 666;cout << f3() << endl;return 0; } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的[C++11]可调用对象绑定器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 西瓜视频草稿箱在哪里
- 下一篇: [PAT乙级]1042 字符统计