Function Objects/Functors函数对象及优势

本文介绍了函数对象(functor)的概念及其在C++标准模板库(STL)中的运用。函数对象不仅可以保存状态,还能作为模板参数使用,使得STL能够灵活地处理各种排序和算法需求。

A function object , or functor , is any type that implements operator(). This operator is referred to as the call operator or sometimes the application operator . The Standard Template Library uses function objects primarily as sorting criteria for containers and in algorithms.

函数对象是任何实现了括号运算符operator()的类型。。。。STL使用函数对象作为容器的排序依据和算法。

Function objects provide two main advantages over a straight function call. The first is that a function object can contain state. The second is that a function object is a type and therefore can be used as a template parameter.

和直接的函数调用相比,函数对象有两个主要的优势,第一个是函数对象可以保持状态,第二个是函数对象是一个类型,所以可以用作模板参数。

 

 

注:个人认为,第一个优势用处很小,尤其是STL里,一般作为排序比较的依据,这种比较规则一般是固定了的,在容器生命周期从始至终都应该是固定的,而在中间通过状态来改变规则的情况很小,即便出现,也要重新创建原来的容器。意义不大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值