Given the following two typedef
s:
typedef void (*pftype)(int);
typedef void ftype(int);
I understand that the first defines pftype
as a pointer to a function that takes one int
parameter and returns nothing, and the second defines ftype
as a function type that takes one int
parameter and returns nothing. I do not, however, understand what the second might be used for.
I can create a function that matches these types:
void thefunc(int arg)
{
cout << "called with " << arg << endl;
}
and then I can create pointers to this function using each:
int main(int argc, char* argv[])
{
pftype pointer_one = thefunc;
ftype *pointer_two = thefunc;
pointer_one(1);
pointer_two(2);
}
When using the function type, I have to specify that I'm creating a pointer. Using the function pointer type, I do not. Either can be used interchangeably as a parameter type:
void run_a_thing_1(ftype pf)
{
pf(11);
}
void run_a_thing_2(pftype pf)
{
pf(12);
}
What use, therefore, is the function type? Doesn't the function pointer type cover the cases, and do it more conveniently?
Also consider this
Since we want it to accept function pointers, by pattern matching the T becomes a function type.
As well as the use you point out (the underlying type of a pointer or reference to a function), the most common uses for function types are in function declarations:
for which one might want to use a
typedef
:and as template parameters:
I just want to point out that I think
function_t *fptr ...
is clearer thanfuncptr_t fptr...
. The first form stated that it must be a pointer type, which is clearer than anything, including the namefuncptr_t
.