Anonymous functions return dynamically allocated values

前端 未结 4 1956
北恋
北恋 2021-01-29 06:12

The question is based on a design pattern solution easily doable in other languages but difficult to implement in C. The narrowed down code is below.

Building on this an

4条回答
  •  被撕碎了的回忆
    2021-01-29 06:24

    First community told me that anonymous functions are not part of C, so the alternate suggestion is to use named functions and pointer to it.

    Secondly a pointer to a parent struct can't receive a pointer to it's derived type (Embedded parent struct) so I can't do much there. I tried using void * but perhaps a solution might exists using memory address and then access some member of the struct without casting to specific types. I'll ask that in another question.

    What I'm missing is the ability to call the super method from the overridden run method in some way?

    src/super.h

    struct Super {
        void (*run)();
    };
    
    struct Super *newSuper();
    

    src/super.c

    static void run() {
        printf("Running super struct\n");
    }
    
    struct Super *newSuper() {
        struct Super *super = malloc(sizeof(struct Super));
        super->run = run;
        return super;
    }
    

    src/Runner.h

    struct Runner {
    
        void (*addFactoryMethod)(struct Super *(*ref)());
    
        void (*execute)();
    };
    
    struct Runner *newRunner();
    

    src/runner.c

    struct Super *(*superFactory)();
    
    void addFactoryMethod(struct Super *(*ref)()) {
        superFactory = ref;
    }
    
    static void execute() {
        struct Super *sup = superFactory(); // calling cached factory method
        sup->run();
    }
    
    struct Runner *newRunner() {
        struct Runner *runner = malloc(sizeof(struct Runner));
        runner->addFactoryMethod = addFactoryMethod;
        runner->execute = execute;
        return runner;
    }
    

    test/runner_test.c

    void anotherRunMethod() {
        printf("polymorphism working\n");
        // how can i've the ability to call the overridden super method in here?
    }
    
    struct Super *newAnotherSuper() {
        struct Super *super = malloc(sizeof(struct Super));
        super->run = anotherRunMethod;
        return super;
    }
    
    void testSuper() {
        struct Runner *runner = newRunner();
        runner->addFactoryMethod(&newAnotherSuper);
        runner->execute();
    }
    
    int main() {
        testSuper();
        return 0;
    }
    

提交回复
热议问题