function call操作符(operator()) 仿函数(functor)

主要是需要某种特殊的东西来代表一整组操作

代表一整组操作的当然是函数,过去通过函数指针实现

所以STL算法的特殊版本所接受的所谓条件或策略或一整组操作都以仿函数的形式呈现

 1 #include <iostream>
 2 
 3 
 4 /*!
 5  * 所谓仿函数(functor)就是使用起来像函数一样的东西,
 6  * 如果你针对某个class进行operator()重载,它就成为一个仿函数、
 7  * 可配接的仿函数??
 8  */
 9 
10 template<class T>
11 struct plus {
12     T operator()(const T&x, const T&y) const {
13         return x + y;
14     }
15 };
16 
17 template<class T>
18 struct minus {
19     T operator()(const T&x, const T&y) const {
20         return x - y;
21     }
22 };
23 
24 int main(int argc, char **argv) {
25     plus<int> plusobj;
26     minus<int> minusobj;
27 
28     std::cout << plusobj(3, 5) << std::endl;
29     std::cout << minusobj(3, 5) << std::endl;
30 
31     std::cout << plus<int>()(3, 5) << std::endl;
32     std::cout << minus<int>()(3, 5) << std::endl;
33 
34     return 0;
35 }

运行结果

8
-2
8
-2

 

posted @ 2018-07-10 10:14  _离水的鱼  阅读(832)  评论(0编辑  收藏  举报