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

前端 未结 3 1111
误落风尘
误落风尘 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:54

    The trick in C is to take advantage of the fact that any kind of function pointer can be cast to any other kind of function pointer:

    #include 
    #include 
    
    typedef void(*emptyfunc)(void);
    typedef emptyfunc (*funcptr2)(int);
    
    funcptr2 strategy(int m)
    {
      printf("Strategy %d.\n", m);
      return (funcptr2)&strategy;
    }
    
    int main (void)
    {
      const funcptr2 strategy2 = (funcptr2)strategy(1);
      const funcptr2 strategy3 = (funcptr2)strategy2(2);
      strategy3(3);
    
      return EXIT_SUCCESS;
    }
    

    Each pointer to a strategy is always in a type that can be called once, and the return value is put back into a form that can be called once again.

    In C++, you would declare a function object:

    class strategy {
      public:
      virtual const strategy& operator()(int) const = 0;
    }
    

    An instance of this class can be called like a function.

提交回复
热议问题