所谓的仿函数(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; }