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?
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.
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.
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.
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.
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
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;
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