To keep it very simple I have a function that passes void (*)(int,int,int) how do I cast to it as a parameter?
example: Function(void (*)(int,int,int) );
I'm expecting to pass parameters here but I got no idea what they are
CodePudding user response:
The declaration of Function expects you to pass it the address of a free function (i.e. one not bound to the instance of a class) that takes three parameters of type int. You didn't specify a return type for Function so for this example I'm going to assume it is void.
#include <iostream>
void Function(void (*)(int, int, int));
void DoSomething(int a, int b, int c)
{
std::cout << "DoSomething called with a=" << a << " b=" << b << " c=" << c;
}
int main()
{
Function(DoSomething);
}
void Function(void (*callback)(int, int, int))
{
std::cout
<< "Function called. Now calling 'callback' at address "
<< callback
<< "\n";
callback(1, 2, 3);
}
In this example main calls Function by passing the address of function DoSomething. The implementation of Function then calls the function it is passed (named callback) and passes 3 arguments 1, 2, and 3.
The result is the following
Function called. Now calling 'callback' at address 00511F55
DoSomething called with a=1 b=2 c=3
You should not need to do any casting to call Function. If you encounter an error or start believing that you should perform a cast to call it you're about to do something terribly wrong.
CodePudding user response:
Is this what you're looking for?
Function(static_cast<void (*)(int,int,int)>(fp))
You might alternatively need const_cast or reinterpret_cast depending on what you're casting...
