6

std::bind を使用してコールバックを提供し、最初にいくつかのパラメーターをバインドしてロジックを抽象化しています。すなわち

void start() {

    int secret_id = 43534;

    //Bind the secret_id to the callback function object
    std::function<void(std::string)> cb = std::bind(&callback, secret_id, std::placeholders::_1);

    do_action(cb);

}

void do_action(std::function<void(std::string)> cb) {

    std::string result = "hello world";
    //Do some things...

    //Call the callback
    cb(result);
}

void callback(int secret_id, std::string result) {

    //Callback can now do something with the result and secret_id

}

したがって、上記の例では、do_action は secret_id について知る必要がなく、他の関数は独自の secret_id を持たなくてもそれを再利用できます。これは、do_action がある種の非同期操作である場合に特に役立ちます。

私の質問は、C のみを使用してパラメーター値を関数ポインターにバインドする方法はありますか?

std::bind をエミュレートしない場合、中立的な do_action() を複雑にすることなく、first() から callback() にデータを渡す別の方法はありますか?

4

4 に答える 4

3

不透明な型とソースで秘密を保持することでそれを行う必要があります。

#include <stdio.h>

// Secret.h

typedef struct TagSecret Secret;
typedef void (*SecretFunction)(Secret*, const char* visible);
void secret_call(Secret*, const char* visible);

// Public.c

void public_action(Secret* secret, const char* visible) {
    printf("%s\n", visible);
    secret_call(secret, visible);
}


// Secret.c

struct TagSecret {
    int id;
};

void secret_call(Secret* secret, const char* visible) {
    printf("%i\n", secret->id);
}

void start() {
    Secret secret = { 43534 };
    public_action(&secret, "Hello World");
}


int main() {
    start();
    return 0;
}

(上記はコールバック関数の登録には対応していません)

于 2013-09-27T10:00:31.790 に答える