#include <iostream>
#include <functional>
#include <list>
#include <algorithm>
#include <typeinfo>
using namespace std;
class Shape
{
private:
int n;
public:
Shape(const int &_n)
:n(_n)
{
}
int draw()
{
cout<<n<<endl;
return 0;//此处为兼容VC6.0.不支持传回void
}
};
template <typename R, typename T>
class my_mem_fun_ref_t
:public unary_function <T, R>
{
private:
R (T::*pmf) ();//定义私有变量(以T为基类的成员函数的指针,返回类型为R)
public:
explicit my_mem_fun_ref_t(R(T::*p)())
:pmf(p)
{
}//显式定义构造函数
R operator() (T& X) const //重载() 接受T类型(引用)
{
return ((X.*pmf)()); //返回此指针所指的成员函数的指针, 也就是返回此功能
}
};
template <typename R,typename T>
my_mem_fun_ref_t<R,T> my_mem_fun_ref(R(T::*f)())//定义通用函数,接受成员函数指针为参数
{
cout<<typeid(R).name()<<endl;
return my_mem_fun_ref_t <R,T>(f);//返回由此指针所构造的函数对象,使之运作
}
int main()
{
list <Shape> ilst;
for (int i = 1; i != 10; ++i) {
ilst.push_back(i);//没有显式定义,故int稳式转化为Shape
}
for_each(ilst.begin(), ilst.end(), my_mem_fun_ref(&Shape::draw));/*my_men_fun_ref_t<R, T>里面的R和T类型是由 my_mem_fun_ref(&Shape::draw)的返回类型和Shape提供的*/
/*测试上面的&Shape::draw是做为my_mem_fun_ref的参数,从而进入 my_mem_fun_ref_t <R,T> (f);构造对像所用
.此对像一旦构造成功,再传入参数 就是调用opertor()*/
return 0;
}