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

 

转载于:https://www.cnblogs.com/Jacket-K/p/9287542.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值