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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With