# 为生存而奔跑

:: 首页 :: 联系 :: 聚合  :: 管理

•

• 积分 - 267197
• 排名 - 83

### 评论排行榜

struct print_obj{

void operator(int a)const{

cout<<a<<endl;
}
};

struct D {
D(int i=0){num=i;}
int num;
};
struct print_D{

void operator()(const D* d)const{

cout<<"I am D. my num="<<d->num<<endl;
}
};

int main()
{
vector<D*> V;

V.push_back(new D(1));
V.push_back(new D(2));
V.push_back(new D);
V.push_back(new D(3));

for_each(V.begin(), V.end(), print_D());
}

I am D. my num=1
I am D. my num=2
I am D. my num=0
I am D. my num=3

struct D {
D(int i=0){num=i;}
void print() { cout << "I'm a D. my num=" << num<< endl; }
int num;
};

int main()
{
vector<D*> V;

V.push_back(new D(1));
V.push_back(new D(2));
V.push_back(new D);
V.push_back(new D(3));

for_each(V.begin(), V.end(), mem_fun(&D::print));
}

如果对STL的某个部分不了解，就去看源码，源码是最好的老师。

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>
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)();
};

struct D {
D(int i=0){num=i;}
void print() { cout << "I'm a D. my num=" << num<< endl; }
int num;
};

int main()
{
vector<D> V;

V.push_back(D(1));
V.push_back( D(2));
V.push_back( D());
V.push_back( D(3));

for_each(V.begin(), V.end(), mem_fun_ref(&D::print));
}

mem_fun对于一些多态的虚函数也十分有用，注意看下面的例子：

struct B {
virtual void print() = 0;
};

struct D1 : public B {
void print() { cout << "I'm a D1" << endl; }
};

struct D2 : public B {
void print() { cout << "I'm a D2" << endl; }
};

int main()
{
vector<B*> V;

V.push_back(new D1);
V.push_back(new D2);
V.push_back(new D2);
V.push_back(new D1);

for_each(V.begin(), V.end(), mem_fun(&B::print));
}

posted on 2009-12-01 18:31 baby-fly 阅读(560) 评论(0)  编辑 收藏 引用 所属分类: Effective STL / C++