I'd like to write this
typedef void (*FunctionPtr)();
using using
. How would I do that?
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.
add_pointer<void()>::type
: Using the suggestion here: groups.google.com/a/isocpp.org/d/msg/std-proposals/xDQR3y5uTZ0/… you can write pointer<function<void>>
.
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();
*
later and get confusing errors.
Jul 26, 2019 at 22:25
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.
How about this syntax for clarity? (Note double parenthesis)
void func();
using FunctionPtr = decltype((func));
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
using
indeed, especially because function pointer identifiers usually resided in the middle of atypedef
statement and move to the front usingusing
. At least that's where I'm lost.