[英]How to static cast throwing function pointer to noexcept in C++17?
C++17 makes noexcept
part of a function's type. C ++ 17使noexcept
成为函数类型的一部分。 It also allows implicit conversions from noexcept
function pointers to potentially throwing function pointers. 它还允许从noexcept
函数指针到潜在抛出函数指针的隐式转换。
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. http://eel.is/c++draft/expr.static.cast#7表示static_cast
可以执行这种转换的反转。
void (*noexcept_again)() noexcept = static_cast<void(*)() noexcept>(ptr_to_throwing);
Unfortunately, both GCC and clang tell me otherwise: https://godbolt.org/z/TgrL7q 不幸的是,GCC和clang都告诉我: https : //godbolt.org/z/TgrL7q
What is the correct way to do this? 这样做的正确方法是什么? Are reinterpret_cast
and C style cast my only options? reinterpret_cast
和C风格是我的唯一选择吗?
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. 可以使用static_cast显式执行任何不包含左值到右值,数组到指针,函数到指针,空指针,空成员指针,布尔值或函数指针转换的标准转换序列的反转。
Currently, a function pointer conversion includes only the conversion from noexcept
to potentially throwing. 目前,函数指针转换仅包括从noexcept
到潜在抛出的转换。 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. 因为你正在执行函数指针转换的反转,所以static_cast
将不起作用,就像你不能static_cast
一个指向数组的指针,或者那里列出的任何其他转换一样。
So yes, reinterpret_cast
would be appropriate and also raises the appropriate alarm bells that should come with discarding noexcept
. 所以,是的, reinterpret_cast
是合适的,并且还会提出适当的警钟,应该放弃noexcept
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.