C++零基礎(chǔ)教程之std:function函數(shù)包裝器
作者:C語言基礎(chǔ)
C++提供了std::function和std::bind統(tǒng)一了可調(diào)用對象的各種操作。不同類型可能具有相同的調(diào)用形式。使用前記得加上functional頭文件。
前言
C++中可調(diào)用對象的雖然都有一個比較統(tǒng)一的操作形式,但是定義方法五花八門,這樣就導(dǎo)致使用統(tǒng)一的方式保存可調(diào)用對象或者傳遞可調(diào)用對象時,會十分繁瑣。C++提供了std::function和std::bind統(tǒng)一了可調(diào)用對象的各種操作。不同類型可能具有相同的調(diào)用形式。使用前記得加上functional頭文件。
包裝普通函數(shù)
- #include <iostream>
- #include <string>
- #include <functional>
- using namespace std;
- int Max(int a, int b)
- {
- return a > b ? a : b;
- }
- void print()
- {
- cout << "無參無返回值" << endl;
- }
- int main()
- {
- function<int(int, int)> funMax(Max);
- cout << funMax(1, 2) << endl;
- function<void()> funPrint(print);
- print();
- printData(funMax, 1, 2);
- return 0;
- }
包裝類的靜態(tài)方法
- #include <iostream>
- #include <string>
- #include <functional>
- using namespace std;
- class Test
- {
- public:
- static void print(int a, int b)
- {
- cout << a + b << endl;
- }
- void operator()(string str)
- {
- cout << str << endl;
- }
- operator FuncPTR()
- {
- return print;
- }
- };
- int main()
- {
- //包裝類的靜態(tài)方法
- function<void(int, int)> sFunc = Test::print;
- sFunc(1, 2);
- return 0;
- }
包裝仿函數(shù)
- #include <iostream>
- #include <string>
- #include <functional>
- using namespace std;
- class Test
- {
- public:
- void operator()(string str)
- {
- cout << str << endl;
- }
- };
- int main()
- {
- //包裝仿函數(shù)
- Test test;
- function<void(string)> funTest = test;
- test("仿函數(shù)");
- return 0;
- }
包裝轉(zhuǎn)換成函數(shù)指針的對象 (operator的隱式轉(zhuǎn)換)
- #include <iostream>
- #include <string>
- #include <functional>
- using namespace std;
- using FuncPTR = void(*)(int, int);
- class Test
- {
- public:
- static void print(int a, int b)
- {
- cout << a + b << endl;
- }
- operator FuncPTR()
- {
- return print;
- }
- };
- int main()
- {
- //包裝轉(zhuǎn)換成函數(shù)指針的對象 (operator的隱式轉(zhuǎn)換)
- Test object;
- function<void(int,int)> funOPE = object;
- funOPE(2, 3);
- return 0;
- }
責任編輯:姜華
來源:
今日頭條