如何在C ++ 17中静态将throwing函数指针转换为noexcept? [英] How to static cast throwing function pointer to noexcept in C++17?

查看:109
本文介绍了如何在C ++ 17中静态将throwing函数指针转换为noexcept?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 17使noexcept成为函数类型的一部分.它还允许从noexcept函数指针到潜在抛出函数指针的隐式转换.

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 static_cast可以执行这种转换的逆过程.

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);

不幸的是,GCC和clang都以其他方式告诉我: https://godbolt.org/z/TgrL7q

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

执行此操作的正确方法是什么? reinterpret_cast和C风格是我唯一的选择吗?

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

推荐答案

您可能已经跳过了重要部分:

You might have skipped over the important part:

任何标准转换序列的倒数不包含左值到右值,数组到指针,函数到指针,空指针,空成员指针,布尔值,或函数指针转换,可以使用static_cast明确执行.

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.

当前,函数指针转换仅包括从noexcept到潜在抛出的转换.因为您正在执行相反的函数指针转换,所以static_cast将不起作用,就像您无法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.

是的,reinterpret_cast是合适的,并且还会发出丢弃noexcept时应附带的适当的警铃.

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

这篇关于如何在C ++ 17中静态将throwing函数指针转换为noexcept?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆