Home > Mobile >  What is the signature of a function that returns another function of the same type?
What is the signature of a function that returns another function of the same type?

Time:05-08

With a something like this:

bool exit = false;

int main() {
    auto & fun = init_function;
    while(!exit) {
        fun = fun();
    }
}

I know I can make it work by casting void* into the right function pointer, but it would be better to know the actual function type.

I'm searching for the declaration syntax of init_function.

CodePudding user response:

There is no such signature. But the premise of such a state machine is not an impossible one, if we apply the fundamental theorem of software engineering: everything can be solved with a layer of indirection.

For instance, we can declare functions returning incomplete types. And so can declare a function type for a function returning an incomplete type. When we complete the type, we can have it store a pointer to a function... of the type we just declared.

struct Ret;
using FunType = auto() -> Ret;

struct Ret {
   FunType *pFunc;
   operator FunType* () { return pFunc; } // Allow implicit conversion back to a function pointer
};

And that's as little as you'd need, really.

Ret init_function() {
    return {init_function}; // Infinite recursion, yay!
}

bool exit = false;

int main() {
    auto *fun = init_function; // Pointer to a function
    while(!exit) {
        fun = fun(); // Call it, get a Ret object, implicitly convert it back to a pointer
    }
}
  • Related