STL中的函數對象實現負數的定義

//
//  main.cpp
//  STL中的函數對象
//
//  Created by mac on 2019/5/2.
//  Copyright © 2019年 mac. All rights reserved.
//  1.是否支持模版繼承?
//  2.模版中存在多個參數?

#include <iostream>
#include <functional>

using namespace std;

/*
 STL在<functional>中爲常見的C++運算符定義了函數對象。其中負號的定義爲:
 template <class T>
 struct negate:public unary_function<T,T>{
    T operator() (const T&x)const{
        return -x;
 }
 };
 
 */


//計算(n,m)之間的和 n+...+m
template <class F>
double sum(F f,int n,int m) {
    double result=0;
    for (int i=n; i<=m; i++) {
        //還有一種簡寫的方式 result+=f(i);
        result+=f.operator()(i);//規範寫法
    }
    return result;
}
int main(int argc, const char * argv[]) {
    // insert code here...
    cout<<sum(negate<double>(),2,5)<<endl;
    return 0;
}

運行結果

-14
Program ended with exit code: 0

Tips

  • 類模版是否支持繼承?
  • 代碼中的struct跟C中的struct不是一回事
  • sum函數中第一個參數,須要傳入一個對象,你看代碼中傳入了個啥玩意?爲何這樣寫不會報錯?
  • 如何理解unary_function<T,T>?
相關文章
相關標籤/搜索