Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a function type used for?

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?

like image 729
Mark Avatar asked Nov 27 '12 17:11

Mark


People also ask

What is the use of type function give an example of it?

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.

What is function type in GO?

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.

What is function write types?

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.


1 Answers

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
like image 153
Mike Seymour Avatar answered Sep 21 '22 04:09

Mike Seymour