日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

[C++11]可调用对象绑定器

發布時間:2023/12/4 c/c++ 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [C++11]可调用对象绑定器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

std::bind用來將可調用對象與其參數一起進行綁定。綁定后的結果可以使用std::function進行保存,并延遲調用到任何我們需要的時候。通俗來說,它主要有兩個作用:

1.將可調用對象與其參數一起綁定成一個仿函數。

2.將多元(參數個數為n,n > 1)可調用對象轉換為一元或者(n -1)元可調用對象,即只綁定部分參數。

綁定器函數使用語法格式如下:

//綁定非類成員函數/變量 auto f = std::bind(可調用對象地址,綁定的參數 / 占位符); //綁定類成員函數/變量 auto f = std::bind(類函數 / 成員地址,類實例對象地址,綁定的參數 / 占位符);

代碼如下:

#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,調用時沒有第二個參數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; }

測試結果:

可調用對象綁定器的使用:

代碼如下:

#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; }

測試結果:

代碼如下:

#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() {//成員函數綁定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; }

測試結果:

可調用對象包裝器的使用:

代碼如下:

#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() {//成員函數綁定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; } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的[C++11]可调用对象绑定器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。