實現 operator() 的類。調用語法與函數指針一致:obj(args)。
核心優勢:可攜帶狀態(附加數據),函數指針做不到。
class Less {
int threshold;
public:
Less(int n) : threshold(n) {}
bool operator()(int value) const { return value < threshold; }
};
// 使用
int arr[] = {50, 30, 9, 7, 20};
auto p1 = std::find_if(std::begin(arr), std::end(arr), Less(10)); // 指向 9
auto p2 = std::find_if(std::begin(arr), std::end(arr), Less(40)); // 指向 30
每個 Less(n) 擁有獨立閾值,靈活復用。
template
int count_if(int* arr, int size, FUNC pred) {
int cnt = 0;
for (int i=0; i
成員函數指針需對象實例調用。函數對象可綁定 this 指針:
template
class MemFun {
void (O::*func)(const char*);
O* obj;
public:
MemFun(void (O::*f)(const char*), O* o) : func(f), obj(o) {}
void operator()(const char* name) { (obj->*func)(name); }
};
class A {
public:
void greet(const char* name) { std::cout << "Hello " << name << "!\n"; }
};
A a;
MemFun caller(&A::greet, &a);
caller("Kitty"); // 輸出 Hello Kitty!
std::mem_fun_ref / std::mem_fun:僅支持 0/1 參數,語法冗長。boost::function:默認支持 10 參數,最多 50,實現極其複雜(模板偏特化 + 宏)。std::function 成為標準。函數對象是 STL 算法靈活性的基石,掌握其定義、狀態攜帶、模板適配與成員函數綁定,是高效使用 C++ 標準庫的關鍵。