Pointers to any function?
You can use a union. There are surely only a finite number of function types that you call via this pointer, and you can put them all in the union.
Firstly, there's no way to declare a function pointer that would be able to accept any function pointer type without a cast. The problem, as you already noted yourself, is that any function pointer declaration immediately assumes a specific return type. So, there's no such thing as full analogue of void *
in function pointer world.
Secondly, any function pointer can be used to store any other function pointer value as long as you force the conversion by using an explicit cast. Of course, in order to perform a proper call through a pointer forcefully converted to a different type you need to convert it back to the original type. I.e. this does not cause any undefined behavior as long as the proper function pointer type is restored at the moment of the call.
In your example if the pointer returned by get_function
really points to a function of double (double)
type, then it is perfectly safe to call that function through cosine
pointer. The fact that the pointer value was stored intermediately in a void (*)()
pointer does not destroy it.
Thirdly, in C language a ()
parameter declaration stands for unspecified number and types of parameters. This is a step in the direction of the "universal" function pointer type that can be used without a cast (as long as you supply proper parameters in the call and as long as the return type matches)
void foo(void);
void bar(int i);
void baz(long i, double x);
int main() {
void (*a[3])() = { foo, bar, baz };
a[0]();
a[1](42);
a[2](5L, 3.1415);
}
But, again, the problem of return type still remains.