概述
仿函数(Functor)又称为函数对象(Function Object),函数对象是一个对象,但是使用的形式看起来像函数调用,实际上也执行了函数调用,因而得名。仿函数的语法普通的函数调用一样,调用仿函数,实际上就是通过类对象调用重载后的operator()运算符。所以作为仿函数的类,必须重载operator()运算符。
仿函数的作用:
- 可替代函数指针,使用更加灵活
- 可存储状态,形成一种类似于闭包的机制
#include <iostream>
using namespace std;
#if 0
class Calculation{
public:
Calculation(int num):m_nCount(num){}
void operator()(int n){
m_nCount += n;
cout<< "m_nCount = " << m_nCount << endl;
}
private:
int m_nCount;
};
void fun(Calculation & cal){
cal(5);
cal(5);
}
int main()
{
Calculation cal(3);
// cal(5);
// cal(5);
// fun(cal);
fun(Calculation(5));
return 0;
}
#else
int CallFunc(int *start, int *end, bool (*pf)(int))
{
int count=0;
for(int *i=start;i!=end+1;i++)
{
count = pf(*i) ? count+(*i) : count;
}
return count;
}
bool Judge(int num)
{
return num%2 ? false : true;
}
int main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int result = CallFunc(a,a+10,Judge);
cout<<result<<endl;
return 0;
}
//class IsGreaterThanThresholdFunctor
//{
//public:
// explicit IsLessThanTenFunctor(int tmp_threshold) : threshold(tmp_threshold){}
// bool operator() (int num) const
// {
// return num>threshold ? true : false;
// }
//private:
// const int threshold;
//};
//int RecallFunc(int *start, int *end, IsGreaterThanThresholdFunctor myFunctor)
//{
// int count=0;
// for(int *i=start;i!=end+1;i++)
// {
// count = myFunctor(*i) ? count+1 : count;
// }
// return count;
//}
//int main()
//{
// int a[5] = {10,100,11,5,19};
// int result = RecallFunc(a,a+4,IsLessThanTenFunctor(10));
// cout<<result<<endl;
// return 0;
//}
#endif
http://c.biancheng.net/view/354.html