仿函数(Functors)

仿函数(functor),就是使一个类的使用看上去象一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了。

例如我们定义一个类:

class X{
    public:
        return-value operator()(arguments) const;
        ...  
};

然后就可以把这个类别的对象当做函数调用

X fo;
...
fo(arg1,arg2)  //等价于fo.operator()(arg1,arg2);

 显然,这种定义形式更为复杂,却又三大妙处:

1.仿函数比一般函数更灵巧,因为它可以拥有状态。

2.每个仿函数都有其型别。因此可以将仿函数的型别当做template参数传递。

3.执行速度上,仿函数通常比函数指针更快。

 

 

仿函数可当做排序准则

 1 #include <iostream>
 2 #include <string>
 3 #include <set>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 class Person{
 8     public:
 9         string firstname() const;
10         string lastname() const;
11         ...        
12 };
13 
14 class PersonSortCriterion{
15     public:
16         bool operator()(const Person&p1,const Person& p2) const {
17             return p1.lastname()<p2.lastname()||
18                     (!(p2.lastname()<p1.lastname())&&
19                     p1.firstname()<p2.firstname());
20         }
21 };
22 
23 int main()
24 {
25     typedef set<Person,PersonSortCriterion> PersonSet;
26     PersonSet coll;
27     PersonSet::iterator pos;
28     for(pos=coll.begin();pos!=coll.end();++pos){
29         ...
30     }
31     ...
32 }
View Code

相关文章: