Home c++ 委派 delegate (中文)
Post
Cancel

c++ 委派 delegate (中文)

Delegate

在 C++ 中實現 delegate(委派)功能,通常可以使用函數對象、std::function 以及 std::bind 來達成。這可以讓你把對某個函數的調用委派給另一個對象或函數。

以下是一個簡單的範例,展示如何使用這些工具來實現類似 delegate 的行為。

使用函數指針

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

// 函數指針類型
typedef void (*DelegateFunc)();

void Function1() {
    std::cout << "Function1 called" << std::endl;
}

void Function2() {
    std::cout << "Function2 called" << std::endl;
}

int main() {
    DelegateFunc delegate = &Function1;
    delegate();  // 輸出:Function1 called

    delegate = &Function2;
    delegate();  // 輸出:Function2 called

    return 0;
}
  1. void: 這表示函數的返回類型是 void,也就是說,這類函數不返回任何值。
  2. (*DelegateFunc): 這表示 DelegateFunc 是一個指向函數的指針。
  3. (): 括號中的空白部分表示這類函數不接受任何參數。

Desktop View

使用 std::function 和 std::bind

這是一個更靈活的方法,可以使用於成員函數、lambda 表達式和自由函數。 而且 c++ 11 後就可以用了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <functional>

// 自由函數
void FreeFunction() {
    std::cout << "FreeFunction called" << std::endl;
}

// 成員函數
class MyClass {
public:
    void MemberFunction() {
        std::cout << "MemberFunction called" << std::endl;
    }
};

int main() {
    std::function<void()> delegate;

    // 委派給自由函數
    delegate = FreeFunction;
    delegate();  // 輸出:FreeFunction called

    // 委派給 lambda 表達式
    delegate = []() {
        std::cout << "Lambda called" << std::endl;
    };
    delegate();  // 輸出:Lambda called

    // 委派給成員函數
    MyClass obj;
    delegate = std::bind(&MyClass::MemberFunction, &obj);
    delegate();  // 輸出:MemberFunction called

    return 0;
}

Desktop View

使用時機

  1. 事件處理:在許多事件驅動的編程環境中,委派函數用於處理事件。例如,在圖形用戶界面(GUI)應用程序中,按鈕點擊或鍵盤輸入等事件需要特定的處理函數來響應。

  2. 回調函數:在異步編程或需要等待某些操作完成後執行後續操作時,回調函數非常有用。委派函數可以用作回調函數,在操作完成後調用,以執行後續的邏輯處理。

  3. 策略模式:在設計模式中,策略模式允許在運行時選擇算法或行為。委派函數可以用於動態設置或改變某些操作的實現方式,增加靈活性。

  4. 高階函數:高階函數是指接受另一個函數作為參數的函數。這種方式廣泛應用於函數式編程,使得操作更加簡潔且具表達力。例如,C++ 的 std::sort 函數可以接受一個比較函數來定義排序的順序。

還有其他情形,但以上是比較常見的情形。

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍