I am trying to write a function that returns a function pointer. Here is my minimal example:
void (*myfn)(int)() // Doesn't work: supposed to be a function called myfn
{ // that returns a pointer to a function returning void
} // and taking an int argument.
When I compile this with g++ myfn.cpp
it prints this error:
myfn.cpp:1:19: error: ‘myfn’ declared as function returning a function
myfn.cpp:1:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
Does this mean I am not allowed to return a function pointer?
You are allowed to return a function pointer, and the correct syntax looks like this:
void (*myfn())(int)
{
}
Complete example:
#include <cstdio>
void retfn(int) {
printf( "retfn\n" );
}
void (*callfn())(int) {
printf( "callfn\n" );
return retfn;
}
int main() {
callfn()(1); // Get back retfn and call it immediately
}
Which compiles and runs like this:
$ g++ myfn.cpp && ./a.out
callfn
retfn
If anyone has a good explanation for why g++'s error message suggests this is not possible, I'd be interested to hear it.
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