Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading