/*******************************************************************
* Copyright (C) stechrayo
* Author : stechrayo
* Create : 2013-4-28 10:51
* Mail : stechrayo@gmail.com
* Blog : http://blog.csdn.net/leiych
*
* Description : 阐述C++中仿函数的基本概念
*
******************************************************************/
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
//print为仿函数
class print{
public:
print(void)
:count(0) {
}
void operator()(int x)
{
cout << x << endl;
++count;
}
public:
int count;
};
int main(void)
{
list<int> ilist;
//初始化
for ( size_t i = 1; i < 10; ++i)
{
ilist.push_back(i);
}
//遍历ilist元素并打印
print p = for_each(ilist.begin(), ilist.end(), print());
//打印ilist元素个数
cout << p.count << endl;
return 0;
}
下面为STL中for_echo的代码:
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));
}
仿函数,顾名思义就是模拟函数的调用。但是在这里,其实是类重载了操作符(),然后在调用操作符的时候,会生成一个无名类,最终在内部还是通过这个无名类调用函数的。请注意上述仿函数中成员变量count=10。更多的,在《STL 源码剖析》里第1.9.2章节里说明。