所謂的仿函數(functor),是行爲像函數,且能像函數同樣工做的東西。ios
一、C語言使用函數指針和回調函數來實現仿函數,例如一個用來排序的函數能夠這樣使用仿函數函數
#include <stdio.h> #include <stdlib.h> int sort_function( const void *a, const void *b) { return *(int*)a-*(int*)b; } int main() { int list[5] = { 54, 21, 11, 67, 22 }; qsort((void *)list, 5, sizeof(list[0]), sort_function);//起始地址,個數,元素大小,回調函數 for (int x = 0; x < 5; x++) { printf("%i\n", list[x]); } return 0; }
二、C++裏,咱們經過在一個類中重載括號運算符 () 的方法來使用仿函數spa
#include <iostream> #include <algorithm> using namespace std; template<typename T> class show { public: void operator()(const T &x) { cout << x << " "; } }; int main() { int list[]={1,2,3,4,5}; for_each(list,list+5,show<int>()); return 0; }
三、C++11中,經過std::function來實現對C++中各類可調用實體(普通函數、Lambda表達式、函數指針、以及其它函數對象等)的封裝,造成一個新的可調用的std::function對象。指針
#include <functional> #include <iostream> using namespace std; std::function< int(int)> Functional; int TestFunc(int a) { return a; } int main() { Functional = TestFunc; int result = Functional(10); cout << "TestFunc:"<< result << endl; }