1.mem_fun和mem_fun_ref
1.用来适配对象的成员函数
2.对于函数f以及对象obj,在obj上调用f的形式有3种:
(1)f(obj); //f是全局函数(非obj成员函数)
(2)obj.f(); //f是obj的成员函数,obj是非指针
(3)obj->f(); f是obj的成员函数,obj是指针
3.然而,在for_each的定义中,只接受形如(1)的调用
template<class _It, class _Fn1>
inline void for_each(_It _First, _It _Last, _Fn1& _Func) {
for(; _First != _Last; _First++)
_Func(*First);
}
4.如果容器中存放的是对象,可以使用mem_fun_ref适配
2.G2.9源代码
template <class _Ret, class _Tp>
class mem_fun_t : public unary_function<_Tp*,_Ret> {
public:
explicit mem_fun_t(_Ret (_Tp::*__pf)()) : _M_f(__pf) {}
_Ret operator()(_Tp* __p) const { return (__p->*_M_f)(); }
private:
_Ret (_Tp::*_M_f)();
};
template <class _Ret, class _Tp>
class mem_fun_ref_t : public unary_function<_Tp,_Ret> {
public:
explicit mem_fun_ref_t(_Ret (_Tp::*__pf)()) : _M_f(__pf) {}
_Ret operator()(_Tp& __r) const { return (__r.*_M_f)(); }
private:
_Ret (_Tp::*_M_f)();
};
template <class _Ret, class _Tp>
inline mem_fun_t<_Ret,_Tp> mem_fun(_Ret (_Tp::*__f)())
{ return mem_fun_t<_Ret,_Tp>(__f); }
template <class _Ret, class _Tp>
inline mem_fun_ref_t<_Ret,_Tp> mem_fun_ref(_Ret (_Tp::*__f)())
{ return mem_fun_ref_t<_Ret,_Tp>(__f); }
3.示例
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class Shape {
public: virtual void display() = 0;
};
class Rect : public Shape {
public: virtual void display() {
cout << "Rect ";
}
};
class Circle : public Shape {
public: virtual void display() {
cout << "Circle ";
}
};
class Square : public Rect {
public: virtual void display() {
cout << "Square ";
}
};
void display(Shape* sha) {
sha->display();
}
struct DeleteElement {
template<typename TElement>
void operator() (const TElement* p)const {
delete p;
}
};
int main() {
vector<Shape*> v;
v.push_back(new Rect);
v.push_back(new Circle);
v.push_back(new Square);
v.push_back(new Circle);
v.push_back(new Rect);
for(int i=0; i<v.size(); i++) {
(v[i])->display();
}
cout << endl;
for_each(v.begin(), v.end(), display);
cout << endl;
for_each(v.begin(), v.end(), mem_fun(&Shape::display));
cout << endl;
/*for(vector<Shape*>::iterator it=v.begin(); it!=v.end(); it++) {
delete (*it);
}*/
for_each(v.begin(), v.end(), DeleteElement());
}
执行结果:
4.注意
1.当new出对象并放入容器时,要在销毁容器前delete那些对象。
2.在有对象继承情况下,建立指针的容器而不是对象的容器
(1)STL容器装入的对象是原始对象的一个拷贝
(2)如果对象很大,拷贝需要大量性能开销
(3)由于继承存在,拷贝会发生slicing