萬盛學電腦網

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

C++ 函式映射表實戰:以 map 與陣列取代 switch/if-else 提升擴展性

動機:當分支過多時的維護困境

面對大量 switch-case 或 if-else if 鏈,程式碼會膨脹、難以維護,且每次新增功能都需修改核心邏輯,違反開放封閉原則。函式映射表將「條件判斷」轉為「查表呼叫」,實現資料驅動設計。

三種映射策略比較

策略查詢複雜度記憶體開銷擴展便利性適用場景
std::mapO(log N)較高(樹節點)極佳(動態增刪)鍵值稀疏、頻繁增減
靜態陣列O(1)低(連續記憶體)一般(需維護索引連續性)鍵值連續、固定集合
虛擬函式/策略模式O(1)中等極佳(多型擴展)行為封裝、需狀態

本文重點示範前兩種;策略模式留待後續補充。

完整範例:動物行為映射表

定義列舉與成員函式指標型別

enum type_func {
    type_begin = -1,
    type_eat, type_sleep, type_walk, type_run,
    type_smile, type_cry, type_jump,
    type_max_size
};

class CAnimal {
public:
    using ptr_func = int (CAnimal::*)(bool);  // 統一簽名:回傳 int、單一 bool 參數
protected:
    static std::map s_map;
    static ptr_func s_array[type_max_size];
public:
    CAnimal() { memset(s_array, 0, sizeof(s_array)); Init(); }

    // 具體行為函式
    int eat(bool = true)  { return printf("eat\n"), 1; }
    int sleep(bool = true){ return printf("sleep\n"), 1; }
    int walk(bool = true) { return printf("walk\n"), 1; }
    int run(bool = true)  { return printf("run\n"), 1; }
    int smile(bool = true){ return printf("smile\n"), 1; }
    int cry(bool = true)  { return printf("cry\n"), 1; }
    int jump(bool = true) { return printf("jump\n"), 1; }

    void Init() {
        s_map[type_eat]   = &CAnimal::eat;
        s_map[type_sleep] = &CAnimal::sleep;
        s_map[type_walk]  = &CAnimal::walk;
        s_map[type_run]   = &CAnimal::run;
        s_map[type_smile] = &CAnimal::smile;
        s_map[type_cry]   = &CAnimal::cry;
        s_map[type_jump]  = &CAnimal::jump;

        s_array[type_eat]   = &CAnimal::eat;
        s_array[type_sleep] = &CAnimal::sleep;
        s_array[type_walk]  = &CAnimal::walk;
        s_array[type_run]   = &CAnimal::run;
        s_array[type_smile] = &CAnimal::smile;
        s_array[type_cry]   = &CAnimal::cry;
        s_array[type_jump]  = &CAnimal::jump;
    }

傳統 switch / if-else 實作(作為基準)

void Process(type_func type) {
    switch (type) {
        case type_eat:   eat(); break;
        case type_sleep: sleep(); break;
        // ... 其他 case
    }
}

Map 映射呼叫

void ProcessByMap(int key, bool val) {
    auto it = s_map.find(static_cast(key));
    if (it != s_map.end() && it->second)
        (this->*it->second)(val);
}

陣列映射呼叫

void ProcessByArray(int key, bool val) {
    if (type_begin < key && key < type_max_size) {
        ptr_func pFun = s_array[key];
        if (pFun) (this->*pFun)(val);
    }
}

運算子多載語法糖

int operator[](int key) {          // 唯讀呼叫
    auto it = s_map.find(static_cast(key));
    return (it != s_map.end() && it->second) ? (this->*it->second)(false) : 0;
}
int operator()(int key, bool val) { // 可讀寫呼叫
    if (type_begin < key && key < type_max_size) {
        ptr_func pFun = s_array[key];
        return pFun ? (this->*pFun)(val) : 0;
    }
    return 0;
}

靜態成員定義(置於 .cpp)

std::map CAnimal::s_map;
CAnimal::ptr_func CAnimal::s_array[type_max_size];

非成員函式映射(全域函式版)

using ptrFun = void(*)(int);
std::map g_map;
ptrFun g_array[type_max_size];

// 初始化
g_map[type_eat] = func_eat;
g_array[type_eat] = func_eat;

效能與選型建議

  • 熱點路徑、固定集合 → 靜態陣列 O(1) 最快。
  • 動態註冊、插件架構 → std::map/unordered_map 靈活。
  • 需攜帶狀態、複雜邏輯 → 策略模式(繼承介面)更物件導向。

現代 C++ 改良方向

  • 使用 std::function + std::unordered_map 支援 Lambda、仿函式、綁定器。
  • 以 constexpr 建構編譯期映射表,消除執行期初始化開銷。
  • 結合 std::variant 或訪問者模式處理多型回傳型別。

函式映射表是「資料驅動設計」的經典實踐,善用它能讓分派邏輯與業務邏輯解耦,大幅降低維護成本。

copyright © 萬盛學電腦網 all rights reserved