The following code does not compile..but is there some way to get a function pointer to return another function pointer that is equivalent to itself?
typedef FunctionPtr (*FunctionPtr)(int, int);
FunctionPtr Second(int, int);
FunctionPtr First(int, int)
{
// do something
return Second;
}
FunctionPtr Second(int, int)
{
// do something
return First;
}
int main()
{
FunctionPtr a = First(1, 2);
FunctionPtr b = a(2, 3);
FunctionPtr c = b(4, 5);
c(5, 6);
}
Short answer: No, you cannot do this directly. You can get close by using void pointers, but it's nonstandard as a void pointer is not guaranteed to be large enough to fit a function pointer. See Guru of the Week #57 for details.
The closest standards-compatible approach is to define a wrapper type for the function pointer:
struct Wrapper;
typedef Wrapper (*FunctionPtr)(int, int);
struct Wrapper {
Wrapper(FunctionPtr ptr): wrapped(ptr) { }
operator FunctionPtr() { return wrapped; }
FunctionPtr wrapped;
};
Now you can write:
Wrapper Second(int, int);
Wrapper First(int, int) {
// do something
return Second;
}
Wrapper Second(int, int) {
// do something
return First;
}
int main() {
FunctionPtr a = First(1, 2);
FunctionPtr b = a(2, 3);
FunctionPtr c = b(4, 5);
c(5, 6);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With