仿函数(functor)又称之为函数对象(function object),其实就是重载了()操作符的struct,没有什么特别的地方。
STL中的部分实现
/*
template<class _InIt, class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Func);
_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);
return (_STD move(_Func));
}
template<class _InIt,class _Fn1> inline
void _For_each(_InIt _First, _InIt _Last, _Fn1& _Func)
{ // perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First);
}
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
class Print
{
public:
void operator()(const T&elm)
{
cout << elm << ' ';
}
};
struct Plus
{
int operator()(const int& x, const int& y) const
{
return x + y;
}
};
int main()
{
int ia[] = { 0, 1, 2, 3, 4, 5 };
int size = sizeof(ia) / sizeof(ia[0]);
vector<int>iv(ia, ia + size);
Print<int> obj;
for_each(iv.begin(), iv.end(),obj);
cout << endl;
for_each(iv.begin(), iv.end(), Print<int>());
int i = 123;
Print<int>obj1;
obj1(i);
int a = 1, b = 2;
Plus obj2;
cout << obj2(a, b) << endl;
return 0;
}