How do I typedef a function pointer with the C++11 using syntax?
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.
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();
http://ideone.com/e1XuYc
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));