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

杀马特。学长 韩版系。学妹 提交于 2020-01-03 06:59:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!