How do I typedef a function pointer with the C++11 using syntax?

C++C++11Typedef

C++ Problem Overview


I'd like to write this

typedef void (*FunctionPtr)();

using using. How would I do that?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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

Solution 3 - C++

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.

Solution 4 - C++

How about this syntax for clarity? (Note double parenthesis)

void func();
using FunctionPtr = decltype((func));

Solution 5 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrubenvbView Question on Stackoverflow
Solution 1 - C++David GView Answer on Stackoverflow
Solution 2 - C++Vadim GoryunovView Answer on Stackoverflow
Solution 3 - C++Andrew TomazosView Answer on Stackoverflow
Solution 4 - C++Leo GoodstadtView Answer on Stackoverflow
Solution 5 - C++SilvesterView Answer on Stackoverflow