Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to static cast throwing function pointer to noexcept in C++17?

C++17 makes noexcept part of a function's type. It also allows implicit conversions from noexcept function pointers to potentially throwing function pointers.

void (*ptr_to_noexcept)() noexcept = nullptr;
void (*ptr_to_throwing)() = ptr_to_noexcept;  // implicit conversion

http://eel.is/c++draft/expr.static.cast#7 says that static_cast can perform the inverse of such a conversion.

void (*noexcept_again)() noexcept = static_cast<void(*)() noexcept>(ptr_to_throwing);

Unfortunately, both GCC and clang tell me otherwise: https://godbolt.org/z/TgrL7q

What is the correct way to do this? Are reinterpret_cast and C style cast my only options?

like image 294
Filipp Avatar asked Aug 21 '19 17:08

Filipp


People also ask

Can you Static cast a pointer?

The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class.

Can you cast a function pointer?

Yes, it can. This is purpose of casting function pointers, just like usual pointers. We can cast a function pointer to another function pointer type but cannot call a function using casted pointer if the function pointer is not compatible with the function to be called.

What type cast do you use to convert a pointer from one type to another?

reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.

What is a static cast in C?

Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types. Static casts are prefered over C-style casts when they are available because they are both more restrictive (and hence safer) and more noticeable.


1 Answers

You might have skipped over the important part:

The inverse of any standard conversion sequence not containing an lvalue-to-rvalue, array-to-pointer, function-to-pointer, null pointer, null member pointer, boolean, or function pointer conversion, can be performed explicitly using static_­cast.

Currently, a function pointer conversion includes only the conversion from noexcept to potentially throwing. Because you're doing the inverse of a function pointer conversion, static_cast will not work, just like you can't static_cast a pointer to an array, or any of the other conversions listed there.

So yes, reinterpret_cast would be appropriate and also raises the appropriate alarm bells that should come with discarding noexcept.

like image 136
chris Avatar answered Sep 17 '22 17:09

chris