I am confused about using C++ function pointers.
using fn_p1 = void(int); // function pointer
using fn_p2 = void (*)(int);
void functional(fn_p1 f) {
f(1);
}
void callback(int value){
// do something
}
int main() {
fn_p2 f = callback; //works
fn_p1 f1 = static_cast<fn_p1>(f); //does not work
fn_p1 f2 = callback; //does not work
fn_p1 f2 = static_cast<fn_p1>(callback); //does not work
functional(f); // works, the argument is form of void(*)(int)
f(1); // works
functional(*f); // works, the argument is dereferenced, void(int)
(*f)(1); // works
return 0;
}
I know there is no difference if you call a function pointer with f(1)
, (*f)(1)
, or (*****f)(1)
.
I don't get how functional(f);
works but fn_p1 f1 = static_cast<fn_p1>(f);
and its variants can not since they define the function pointer as using fn_p1 = void(int);
.
Could anyone explain how the function pointer works or how the compiler deals with it?