Lambda函數:
外部變量{函數體}
舉例:
auto func = [&ret](n){ret = n+100;};
函數模板:
template<typename 模板參數>
舉例:
template<typename Func>
void go(Func f){
f(b);
}
組合起來使用,
test():定義一個匿名函數func,把匿名函數func 傳入for_student這個模板函數中,打印出總分數ret。
func:將每個分數累加后保存在外部變量ret
for_student的函數體:遍歷學生分數的代碼,每次遍歷執行do函數,
vector<int> vec_scores;
template<typename Func>
void for_student(Func do){
for(auto &s:vec_scores)
do(s);
}
void test(){
int ret= 0;
auto func = [&ret](int score){ret += score;};
go(func);
printf("all score:%d",ret);
}
匿名函數+函數模板一般使用在下列的情況中,
比如有50個學生分數,需要遍歷計算學生分數總和,需要遍歷計算學生前十名,需要遍歷計算學生不及格人數等。
共同的一個過程就是遍歷,每個函數都寫一遍遍歷,則多出很多冗余代碼。
將遍歷過程寫在函數模板中,然后將每次遍歷需要的操作寫入匿名函數中,將匿名函數傳到函數模板中,每次遍歷后執行就好了。
這樣就實現了共用遍歷。
注意:
如果模板函數聲明和定義分別在h和cpp文件中,那模板函數只能在本類中被調用。
如果想在其他類中也調用模板函數,則需要聲明和定義都寫在.h文件中。因為C++要求模板函數的聲明和實現對引用者必須都可見。
類似:
//test.h
class Test{
public:
template<typename T>
void compare(const T& v1, const T& v2)
{
if(v1 < v2)
cout << "v1 < v2" << endl;
if(v1 > v2)
cout << "v1 > v2" << endl;
}
};
//main.cpp
#include "test.h"
void main(){
Test test;
int a=1,b=2;
test.compare(a,b);
}