網站首頁 編程語言 正文
除了容器有適配器之外,其實函數也提供了適配器,適配器的特點就是將一個類型改裝成為擁有子集功能的新的類型。其中函數的適配器典型的就是通過std::bind
來實現。
std::bind函數定義在頭文件functional中,是一個函數模板,它就像一個函數適配器,接受一個可調用對象(callable object),生成一個新的可調用對象來“適應”原對象的參數列表。一般而言,我們用它可以把一個原本接收N個參數的函數fn,通過綁定一些參數,返回一個接收M個(M可以大于N,但這么做沒什么意義)參數的新函數。同時,使用std::bind函數還可以實現參數順序調整等操作。
如可調用 (Callable) 中描述,調用指向非靜態成員函數指針或指向非靜態數據成員指針時,首參數必須是引用或指針(可以包含智能指針,如 std::shared_ptr 與 std::unique_ptr),指向將訪問其成員的對象。
#include <random> #include <iostream> #include <memory> #include <functional> void f(int n1, int n2, int n3, const int& n4, int n5) { std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n'; } int g(int n1) { return n1; } struct Foo { void print_sum(int n1, int n2) { std::cout << n1+n2 << '\n'; } int data = 10; }; int main() { using namespace std::placeholders; // 對于 _1, _2, _3... // 演示參數重排序和按引用傳遞 int n = 7; // ( _1 與 _2 來自 std::placeholders ,并表示將來會傳遞給 f1 的參數) auto f1 = std::bind(f, _2, 42, _1, std::cref(n), n); n = 10; f1(1, 2, 1001); // 1 為 _1 所綁定, 2 為 _2 所綁定,不使用 1001 // 進行到 f(2, 42, 1, n, 7) 的調用 // 嵌套 bind 子表達式共享占位符 auto f2 = std::bind(f, _3, std::bind(g, _3), _3, 4, 5); f2(10, 11, 12); // 進行到 f(12, g(12), 12, 4, 5); 的調用 // 常見使用情況:以分布綁定 RNG std::default_random_engine e; std::uniform_int_distribution<> d(0, 10); std::function<int()> rnd = std::bind(d, e); // e 的一個副本存儲于 rnd for(int n=0; n<10; ++n) std::cout << rnd() << ' '; std::cout << '\n'; // 綁定指向成員函數指針 Foo foo; auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1); f3(5); // 綁定指向數據成員指針 auto f4 = std::bind(&Foo::data, _1); std::cout << f4(foo) << '\n'; // 智能指針亦能用于調用被引用對象的成員 std::cout << f4(std::make_shared<Foo>(foo)) << '\n' << f4(std::make_unique<Foo>(foo)) << '\n'; }
輸出:
2 42 1 10 7
12 12 12 4 5
1 5 0 2 0 8 2 2 10 8
100
10
10
10
原文鏈接:https://www.cnblogs.com/xutopia/archive/2022/01/05/15768939.html
相關推薦
- 2022-06-18 kubernetes(k8s)安裝metrics-server實現資源使用情況監控方式詳解_云其它
- 2023-04-16 c#?成員類型訪問權限低于字段本身的實現_C#教程
- 2022-07-22 git提交代碼設置某些文件不可上傳
- 2022-06-22 Git?Bash終端默認路徑的設置查看修改及拓展圖文詳解_其它綜合
- 2023-05-08 Python隨機生成8位密碼的示例詳解_python
- 2022-10-23 Oracle中for循環的使用方法_C#教程
- 2022-07-04 Android自定義view利用PathEffect實現動態效果_Android
- 2023-07-05 mybatis-plus引入及其代碼生成器
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支