更多文章欢迎访问 程序员小非 博客
定义
functor的英文解释为something that performs a function,即其行为类似函数的东西。C++中的仿函数是通过在类中重载()运算符实现,使你可以像使用函数一样来创建类的对象。
C中是怎么实现这个功能的
使用指针函数和回调函数,比如qsort的比较函数
#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); //起始地址,个数,元素大小,回调函数
int x;
for (x = 0; x < 5; x++)
printf("%i\n", list[x]);
return 0;
}
C++ 中的仿函数
- 一个例子(增加任意常数)
// this is a functor
struct add_x {
add_x(int x) : x(x) {
}
int operator()(int y) {
return x + y; }
private:
int x;
};
// usage:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std