仿函數是重載了 operator() 的類或結構體,其對象可像函數一樣調用。STL 算法(如 find_if, sort)接受仿函數作為策略參數,比函數指針更靈活(可攜帶狀態、內聯優化)。
template <class T>
struct GreaterThan {
T threshold;
GreaterThan(const T& t) : threshold(t) {}
bool operator()(const T& val) const {
return val >= threshold;
}
};
// 使用
list<int> lst = {12, 178, 200};
auto it = find_if(lst.begin(), lst.end(), GreaterThan<int>(100));
if (it != lst.end()) cout << "found: " << *it << endl;
兩者調用語法相同,但仿函數是類型,可作為模板參數傳遞,編譯器更易內聯優化;函數指針是運行期值,難以內聯。示例:
bool gt_func(int a, int b) { return a >= b; }
using FuncPtr = bool(*)(int,int);
struct GT {
bool operator()(int a, int b) const { return a >= b; }
};
int main() {
list<int> lst = {10, 110, 120};
FuncPtr pf = gt_func;
GT gt_obj;
for (int v : lst) cout << pf(v, 100) << ' '; // 函數指針調用
for (int v : lst) cout << gt_obj(v, 100) << ' '; // 仿函數調用
}
<functional> 提供:
plus, minus, multiplies, divides, modulus, negateequal_to, not_equal_to, greater, less, greater_equal, less_equallogical_and, logical_or, logical_not用法:sort(v.begin(), v.end(), greater<int>()) 降序排序。
繼承 unary_function 或 binary_function(C++11 已棄用)可提供 argument_type, result_type 等型別別名,方便 STL 內部萃取。
仿函數是 STL 泛型編程核心:將操作封裝為可攜帶狀態的類型,支持模板參數傳遞、內聯優化、類型萃取。掌握自定義仿函數編寫與標準庫預定義仿函數使用,是高效使用 STL 算法的關鍵。