Given the following two typedefs:
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?
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: