How to write a function pointer to a function returning a function pointer to a function?

前端 未结 3 1121
误落风尘
误落风尘 2021-02-14 13:14

I want to assign a function\'s address to a function pointer, but the function to be addressed returns a function pointer with the same signature as itself, causing it to recurs

3条回答
  •  被撕碎了的回忆
    2021-02-14 13:39

    I suspect what you are trying to do is a more complex version of something like this:

    typedef MainLoop *MainLoop(); // not legal
    
    extern MainLoop* main_loop_1();
    extern MainLoop* main_loop_2();
    
    MainLoop* main_loop_1()
    {
        // do some work here
        return main_loop_2;
    }
    
    MainLoop* main_loop_2()
    {
        // do some work here
        return main_loop_1;
    }
    
    int main()
    {
        MainLoop f = main_loop_1;
    
        for (;;) {
          f = f();
        }
    }
    

    A workaround is to wrap the function pointer in a struct:

    struct MainLoop {
        MainLoop (*function_ptr)(); // legal
    };
    
    extern MainLoop main_loop_1();
    extern MainLoop main_loop_2();
    
    MainLoop main_loop_1()
    {
        // do some work here
        return {main_loop_2};
    }
    
    MainLoop main_loop_2()
    {
        // do some work here
        return {main_loop_1};
    }  
    
    int main()
    {
        MainLoop f{main_loop_1};
    
        for (;;) {
           f = f.function_ptr();
        }
    }
    

提交回复
热议问题