Function Returning Itself

后端 未结 9 714
鱼传尺愫
鱼传尺愫 2020-11-27 04:59

Is it possible to declare some function type func_t which returns that type, func_t?

In other words, is it possible for a function to retur

9条回答
  •  悲&欢浪女
    2020-11-27 05:12

    Assume the function definition

    T f(void)
    {
      return &f;
    }
    

    f() returns a value of type T, but the type of the expression &f is "pointer to function returning T". It doesn't matter what T is, the expression &f will always be of a different, incompatible type T (*)(void). Even if T is a pointer-to-function type such as Q (*)(void), the expression &f will wind up being "pointer-to-function-returning-pointer-to-function", or Q (*(*)(void))(void).

    If T is an integral type that's large enough to hold a function pointer value and conversion from T (*)(void) to T and back to T (*)(void) is meaningful on your platform, you might be able to get away with something like

    T f(void)
    { 
      return (T) &f;
    }
    

    but I can think of at least a couple of situations where that won't work at all. And honestly, its utility would be extremely limited compared to using something like a lookup table.

    C just wasn't designed to treat functions like any other data item, and pointers to functions aren't interchangeable with pointers to object types.

提交回复
热议问题