// 1. typedef 簡化型別名稱
using CompareFunc = bool(*)(int, int); // C++11 別名語法
// 舊式:typedef bool (*CompareFunc)(int, int);
// 2. 目標函式
bool ascending(int a, int b) { return a < b; }
bool descending(int a, int b) { return a > b; }
// 3. 宣告變數並指派
CompareFunc cmp = ascending; // 隱式取址
// 或明確:CompareFunc cmp = &ascending;
// 4. 呼叫
bool result = cmp(3, 5); // false (3 < 5)
cmp = descending;
result = cmp(3, 5); // true (3 > 5)
void customSort(int* arr, int n, CompareFunc cmp)
{
// 簡單氣泡排序示範
for (int i = 0; i < n-1; ++i)
for (int j = 0; j < n-i-1; ++j)
if (cmp(arr[j+1], arr[j])) // 依 cmp 決定順序
std::swap(arr[j], arr[j+1]);
}
int main()
{
int a[] = {5, 2, 8, 1, 9};
customSort(a, 5, ascending); // 1 2 5 8 9
customSort(a, 5, descending); // 9 8 5 2 1
}
C++11 引入 std::function 統一可呼叫物件包裝器,支援函式指標、Lambda、仿函式、std::bind 結果。
#include
#include
#include
void modernSort(std::vector& v, std::function cmp)
{
std::sort(v.begin(), v.end(), cmp);
}
int main()
{
std::vector v = {5, 2, 8, 1, 9};
// Lambda 直接傳遞
modernSort(v, [](int a, int b){ return a < b; }); // 升冪
// 捕捉外部變數
int threshold = 5;
auto countGt = [threshold](int x){ return x > threshold; };
int cnt = std::count_if(v.begin(), v.end(), countGt);
// std::bind 綁定成員函式
struct Processor { bool check(int x, int y) { return x > y; } };
Processor p;
auto bound = std::bind(&Processor::check, &p, std::placeholders::_1, 10);
modernSort(v, bound); // 以 10 為基準
}
| 場景 | 角色 | 回呼用途 |
|---|---|---|
| 事件處理 (GUI、網路) | 框架 | 使用者註冊 onClick/onReceive/onError |
| 非同步 I/O 完成 | IOCP/epoll/kqueue | 完成通知回呼處理資料 |
| 泛型演算法自訂 | STL/std::sort, std::find_if | 比較、判斷、轉換邏輯外部化 |
| 插件/擴充架構 | 主程式 | 動態載入模組註冊回呼介面 |
| 訊號/槽 | Qt/Signals2 | 解耦發送者與接收者 |
(ud)->onEvent(event);
}
};
Handler h;
registerCallback(&Handler::staticWrapper, &h); // 傳遞 this 指標作為 userData
std::function + Lambda (可能內聯)。std::function 有型別抹除開銷 (堆積配置、虛函式呼叫),效能敏感場合優先用模板參數:template
void fastSort(int* arr, int n, F cmp) { // cmp 為具體型別,可內聯
for (int i=0;i