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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

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

std::bind用來將可調(diào)用對象與其參數(shù)一起進(jìn)行綁定。綁定后的結(jié)果可以使用std::function進(jìn)行保存,并延遲調(diào)用到任何我們需要的時(shí)候。通俗來說,它主要有兩個(gè)作用:

1.將可調(diào)用對象與其參數(shù)一起綁定成一個(gè)仿函數(shù)。

2.將多元(參數(shù)個(gè)數(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í)例對象地址,綁定的參數(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í)沒有第二個(gè)參數(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)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。