1

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
LTBS46
  • 205
  • 1
  • 10
  • The return type isn't really part of the function *signature*, to nitpick. With that said, you might want to learn about [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function). – Some programmer dude May 08 '22 at 11:19
  • @Someprogrammerdude `std::function` by itself also won't help here. It can't be recursive either. – user17732522 May 08 '22 at 11:21
  • @Someprogrammerdude indeed but if I want to write a function i still need it and while `std::function` is useful it doesn't solve my problem (or if does i didn't see it) – LTBS46 May 08 '22 at 11:21
  • 1
    @LTBS46 What is your problem that you are trying to solve? Your question is very sparse on information. The straight-forward answer is that such function types are impossible. – user17732522 May 08 '22 at 11:23
  • 1
    That function is impossible, there is no fixed point for this recurrence. Is this XY problem? What are you trying to do? Can `func` just return a callable object? – Quimby May 08 '22 at 11:24
  • Does this answer your question? [Declaration of function returning a function pointer](https://stackoverflow.com/questions/15644088/declaration-of-function-returning-a-function-pointer) – paolo May 08 '22 at 11:28

1 Answers1

2

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
    }
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458