码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-25 11:58:18      阅读:133      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!