Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Function Pointer to Self?

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);
}
like image 219
CuriousGeorge Avatar asked May 07 '11 19:05

CuriousGeorge


1 Answers

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);
}
like image 152
hammar Avatar answered Oct 06 '22 01:10

hammar