Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a function pointer with a trailing return type

There are some Stack Overflow users who strongly advocate always using the new C++11 trailing return type convention when writing functions, such as main()->int. I can see advantages, as it makes the notation uniform. However, when declaring a function pointer, I cannot find any way of using a trailing return form, i.e. can declare either

typedef int(*fp)(int);

or

using fp = int(*)(int);

for a function pointer taking an int and returning an int.

Is there a way of using the new trailing return syntax in declaring such a function pointer? For example, something like

using fp = (*)(int)->int;

but this doesn't compile. If not, is there a reason why the new syntax is not applicable to function pointers?

like image 582
vsoftco Avatar asked Dec 15 '14 05:12

vsoftco


People also ask

Can the return type of a function be pointer?

Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.

What is trailing return type in C++?

The trailing return type feature removes a C++ limitation where the return type of a function template cannot be generalized if the return type depends on the types of the function arguments.

Can function return function pointer in C?

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.

When would you use a pointer to a function?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.


2 Answers

You have to use auto

using fp = auto (*)(int) -> int; typedef auto (*fp)(int) -> int; // alternatively 

Trailing return type syntax means you put the auto before the function name to indicate that the return type follows (or in the case of c++14, should be deduced). For function pointers, the same rule applies except that it can't deduce it (for obvious reasons).

This is true for functions as well though, your example

main() -> int {... } 

is not valid either without the preceding auto

like image 116
Ryan Haining Avatar answered Oct 15 '22 02:10

Ryan Haining


You want one of these depending on whether you are using using declaration or a typedef:

using fp = auto (*)(int)->int; typedef auto (*gp)(int) -> int; 
like image 40
Dietmar Kühl Avatar answered Oct 15 '22 00:10

Dietmar Kühl