1 #include <iostream> 2 #include <functional> 3 4 //函數指針寫法 5 typedef int(*FuncPoint)(const int&); 6 7 8 std::function<int(const int &)> Function; 9 10 //普通函數 11 int FuncDemo(const int &value) 12 { 13 std::cout << "普通函數\t:" << value << "\n"; 14 return value; 15 } 16 17 //lamda函數 18 auto lmdFuc = [](const int &value) -> int 19 { 20 std::cout << "lamda函數\t:" << value << "\n"; 21 return value; 22 }; 23 24 //仿函數 25 class Functor 26 { 27 public: 28 int operator()(const int &value) 29 { 30 std::cout << "仿函數\t:" << value << "\n"; 31 return value; 32 } 33 }; 34 35 //類內靜態函數和類成員函數 36 class Testclass 37 { 38 public: 39 int TestDemo(const int &value) 40 { 41 std::cout << "類內成員函數\t:" << value << "\n"; 42 return value; 43 } 44 45 static int TestStatic(const int &value) 46 { 47 std::cout << "類內靜態成員函數\t:" << value << "\n"; 48 return value; 49 } 50 }; 51 52 53 int main() 54 { 55 //以往函數指針調用 56 FuncPoint Func(FuncDemo); 57 Func(10); 58 //普通函數 59 Function = FuncDemo; 60 Function(10); 61 62 //lamda函數 63 Function = lmdFuc; 64 Function(20); 65 66 //仿函數(函數對象) 67 Functor Fobj; 68 Function=Fobj; 69 Function(30); 70 71 //類內成員函數(需要bind()) 72 Testclass testclass; 73 Function=std::bind(&Testclass::TestDemo,testclass,std::placeholders::_1); 74 Function(40); 75 76 //類內靜態成員函數 77 Function=Testclass::TestStatic; 78 Function(50); 79 80 81 return 0; 82 }
- 關於可調用實體轉換為
std::function
對象需要遵守以下兩條原則:- 轉換后的
std::function
對象的參數能轉換為可調用實體的參數; - 可調用實體的返回值能轉換為
std::function
對象的返回值。
- 轉換后的
std::function
對象最大的用處就是在實現函數回調,使用者需要注意,它不能被用來檢查相等或者不相等,但是可以與NULL或者nullptr進行比較。
為什么加入std::function;
好用並實用的東西才會加入標准的。因為好用,實用,我們才在項目中使用它。std::function
實現了一套類型消除機制,可以統一處理不同的函數對象類型。以前我們使用函數指針來完成這些;現在我們可以使用更安全的std::function
來完成這些任務。