Reputation: 76579
I'd like to write this
typedef void (*FunctionPtr)();
using using
. How would I do that?
Upvotes: 242
Views: 103399
Reputation: 421
Another approach might using auto return type with trailing return type.
using FunctionPtr = auto (*)(int*) -> void;
This has the arguable advantage of being able to tell something is a function ptr when the alias begins with "auto(*)" and it's not obfuscated by the identifier names.
Compare
typedef someStructureWithAWeirdName& (FunctionPtr*)(type1*, type2**, type3<type4&>);
with
using FunctionPtr = auto (*)(type1*, type2**, type3<type4&>) -> someStructureWithAWeirdName&;
Disclaimer: I took this from Bean Deane's "Easing into Modern C++" talk
Upvotes: 8
Reputation: 781
The "ugliness" can also be taken away if you avoid typedef-ing a pointer:
void f() {}
using Function_t = void();
Function_t* ptr = f;
ptr();
Upvotes: 68
Reputation: 96810
It has a similar syntax, except you remove the identifier from the pointer:
using FunctionPtr = void (*)();
Here is an Example
If you want to "take away the uglyness", try what Xeo suggested:
#include <type_traits>
using FunctionPtr = std::add_pointer<void()>::type;
And here is another demo.
Upvotes: 270
Reputation: 2627
How about this syntax for clarity? (Note double parenthesis)
void func();
using FunctionPtr = decltype((func));
Upvotes: 10
Reputation: 68668
You want a type-id
, which is essentially exactly the same as a declaration except you delete the declarator-id
. The declarator-id
is usually an identifier, and the name you are declaring in the equivilant declaration.
For example:
int x
The declarator-id
is x
so just remove it:
int
Likewise:
int x[10]
Remove the x
:
int[10]
For your example:
void (*FunctionPtr)()
Here the declarator-id
is FunctionPtr
. so just remove it to get the type-id
:
void (*)()
This works because given a type-id
you can always determine uniquely where the identifier would go to create a declaration. From 8.1.1 in the standard:
It is possible to identify uniquely the location in the [type-id] where the identifier would appear if the construction were a [declaration]. The named type is then the same as the type of the hypothetical identifier.
Upvotes: 16