首页 > 其他 > 详细

使用函数对象与使用函数的比较

时间:2015-08-25 11:56:10      阅读:272      评论:0      收藏:0      [点我收藏+]

1.使用函数对象,可以让函数变得有状态。而且可以在运行期再初始化。

2.函数对象通常比寻常函数速度快。

 

template<int theValue>
void add(int& elem){
    elem += theValue;
}

class AddValue{
private:
    int theValue;
public:
    AddValue(int v) : theValue(v){}
    void operator()(int& elem) const {
        elem += theValue;
    }
};

void f1(){
    vector<int> coll;
    ```
    int n = 10;
    
    //error 
    for_each(coll.begin(),coll.end(),add<n>);   
    
    //OK
    for_each(coll.begin(),coll.end(),AddValue(n));
}

 

使用函数对象与使用函数的比较

原文:http://www.cnblogs.com/cycxtz/p/4757016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!