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?
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object.
Details. A function type describes the set of all functions with the same parameter and result types. The value of an uninitialized variable of function type is nil . The parameter names are optional.
There are four different patterns to define a function − Functions with no argument and no return value. Functions with no argument but a return value. Functions with argument but no return value. Functions with argument and a return value.
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:
void f(); // declares a function f, of type void()
for which one might want to use a typedef
:
typedef void ft(some, complicated, signature);
ft f;
ft g;
// Although the typedef can't be used for definitions:
void f(some, complicated, signature) {...}
and as template parameters:
std::function<void()> fn = f; // uses a function type to specify the signature
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With