问题
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?
回答1:
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
.
来源:https://stackoverflow.com/questions/57596276/how-to-static-cast-throwing-function-pointer-to-noexcept-in-c17