typedef void (*func_int) (int); //This would make the pointer to function accessible by the name func_int
void func (func_int func name); //YOu can use that as a parameter
func_int varname = &name;// And Create new objects :)
void a_func(void (*func)())
func(); // this should work
(*func)(); // more explicit
std::cout << "test\n";
a_func(test); // this should work
a_func(&test); // more explicit
When you have a function, you can do two things with it: call it or take its address. If you are not calling it, you are taking its address, which is why test and &test both evaluate to the address. You also do not need to dereference the pointer to call it, which is why func() and (*func)() both work. You can do crazy stuff like (*&*&*&******&func)(); too, but that should be reserved for obfuscated code contests. ;)
void* this_func = func;
Unfortunately, void pointers and function pointers are not compatible. Void pointers only work for object types, so you would need to do something like this:
void (*this_func)() = func;
Like Sky Diploma showed, a typedef makes the declaration easier:
typedef void (*pf_t)();
pf_t this_func = func;
But be careful because Sky Diploma's code should not compile. There are minor syntax errors that are not worth mentioning, but a real error is here:
func_int varname = &name;
Always be careful to match the level of indirection. &name is a pointer to func_int, not a func_int, so the level of indirection for the right hand side does not match the left hand side. The compiler should throw an error for this, and the fix is to remove the & operator from the right hand side.
Is it a general rule that the level of indirection on both sides of the = operator should be equivlant?
The general rules is that both sides of the = operator need to have the same type or a compatible enough type for an implicit conversion. Different levels of indirection are neither the same type nor compatible.
//since cos and sin have an overloaded function float cos(float), and float sin(float), It works, although its not tested.
but if you have your own drawFunction with a prototype for example
like this , float myDraw(char); //draws letters,
and you try to pass it to drawGraph(myDraw); //Then it would
be an error because of non-matching signature.