簡體   English   中英

向函數指針添加參數

[英]Add a parameter to a function pointer

我正在使用函數指針來委托 C 中的狀態。

// states
void state1(int first, int second) {
    ...
}

void state2(int first, int second) {
    ...
}

// state pointer
void (*current_state)(int, int);

// state logic
if (condition1) {
    current_state = &state_1;
} else if (condition2) {
    current_state = &state_2;
}

// do the thing
(*current_state)(1, 2);

現在我處於給定參數不再足夠的地步,因此需要第三個參數。 由於我不想更改所有狀態,我想知道是否可以將准常量參數與指針一起傳遞。 像這樣的東西:

void state3(int first, int second, int third) {
    ...
}

// state logic
...
else if (condition3) {
    // calculate the constant third argument
    int param3 = 0;

    current_state = &state_3(int, int, param3);
}

我有辦法讓它發揮作用嗎?

好吧,我不確定我會推薦它,但是您可以執行以下操作:

#include    <stdlib.h>
#include    <stdio.h>
typedef int pfun();
int alice( int a, int b)        { return b; }
int bob( int a, int b, int c)   { return c;     }

int main( )
{
pfun*   f;
    f = alice;
    printf( "%d\n", f( 1, 2, 3));
    f = bob;
    printf( "%d\n", f( 1, 2, 3));

    return EXIT_SUCCESS;
}

這與

gcc -o funp -Wall  funp.c

沒有警告,並且運行正常。

關鍵是像

int f();

說f是一個返回int的函數,帶有未指定的參數。 不利之處在於,編譯器無法檢查參數是否為正確的類型。

您可以傳遞*void指針並將其強制轉換為狀態函數中的具體類型。 所有狀態功能將具有相同的簽名。 像這樣:

// states
struct state1_args {
    int first;
    int second;
};

struct state2_args {
    float first;
    float second;
    float third;
};

void state1(void* state_args) {
    struct state1_args* args = (struct state1_args*)state_args;
    use(args->first);
    ...
}

void state2(void* state_args) {
    struct state2_args* args = (struct state2_args*)state_args;
    use(args->third);
    ...
}

// state pointer
void (*current_state)(void*);

// state logic
if (condition1) {
    current_state = &state_1;
    current_state_args = &args_1;
} else if (condition2) {
    current_state = &state_2;
    current_state_args = &args_2;
}

// do the thing
(*current_state)(current_state_args);

與您的簽名相同

// state pointer
void (*current_state)(int, int);

這不可能。 您必須更改狀態簽名,或者更改如何從state3中刪除參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM