萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 函式指標與回呼函式完整實作指南

核心概念

  • 函式指標:指向可執行程式碼記憶體位址的指標,型別包含回傳型別與參數列表。
  • 回呼函式:將函式指標作為引數傳遞給另一個函式,由被呼叫者在適當時機「回呼」執行。實現控制反轉、事件驅動、泛型演算法自訂行為。

函式指標宣告與使用

// 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++:std::function 與 Lambda

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解耦發送者與接收者

C 風格回呼與 C++ 類別成員函式指標

(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
copyright © 萬盛學電腦網 all rights reserved