标准mem_fun_ref只能将数据交给类自己来处理,而不能由其它类来处理。下面这个mem_fun_ref可以将数据交给其它的类来处理.
// TEMPLATE CLASS mem_fun_ref_t
template<class _Result,
class _container,
class _Ty>
class mem_fun_ref_t
: public std::binary_function<_container,_Ty, _Result>
{ // functor adapter (*left.*pfunc)(), non-const *pfunc
public:
explicit mem_fun_ref_t(_container& c,_Result (_container::*_Pm)(_Ty&))
: _Pmemfun(_Pm),_c(c)
{ // construct from pointer
}
_Result operator()(_Ty& _Param) //const
{ // call function
return ((_c.*_Pmemfun)(_Param));
}
private:
_Result (_container::*_Pmemfun)(_Ty &); // the member function pointer
_container& _c;
};
template<class _Result,
class _Container,
class _Ty> inline
mem_fun_ref_t<_Result, _Container,_Ty> mem_fun_ref(_Container& _c,_Result (_Container::*_Pm)(_Ty&))
{ // return a mem_fun_ref_t functor adapter
return (mem_fun_ref_t<_Result,_Container, _Ty>(_c,_Pm));
}
class Int
{
public:
explicit Int(int i):m_i(i){}
void print1()
{}
private:
int m_i;
};
class aaaa
{
public:
aaaa(){};
~aaaa(){};
void test(Int& i)
{
};
};
void ttt()
{
aaaa bb;
int a[]={1,2,3,4,5,6};
std::vector<Int> va;
va.push_back(Int(1));
for_each(va.begin(),va.end(),mem_fun_ref<void,aaaa,Int>(bb,&aaaa::test));
}