What is a function type used for?

2020-08-09 11:21发布

问题:

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?

回答1:

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


回答2:

Also consider this

template<typename T>
void f(T*);

Since we want it to accept function pointers, by pattern matching the T becomes a function type.



回答3:

I just want to point out that I think function_t *fptr ... is clearer than funcptr_t fptr.... The first form stated that it must be a pointer type, which is clearer than anything, including the name funcptr_t.