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

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));
}

 

posted @ 2015-08-25 11:49  forxtz  阅读(148)  评论(0)    收藏  举报