Emulating std::bind in C

前端 未结 4 1734
北荒
北荒 2021-01-12 16:43

I\'m using std::bind to provide a callback while abstracting some logic by binding some parameters first. i.e.

void start() {

    int secret_id = 43534;

           


        
4条回答
  •  执念已碎
    2021-01-12 17:20

    An opaque type and keeping secret in a source should do it:

    #include 
    
    // 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;
    }
    

    (The above does not address registering callback functions)

提交回复
热议问题