c++ - 将函数指针转换为 noexcept 指定的函数指针

标签 c++ function-pointers noexcept

假设我有这些声明:

using fp_type = void(*)();
using fp2_type = void(*)() noexcept;

void func(){}
fp_type fp(func);

转换 fp2_type(fp) 是否合式?反过来(将 noexcept 指定的函数指针转换为没有 noexcept 说明符的函数指针)?

最佳答案

这在 C++14 及更早版本中是病式的:

using fp2_type = void(*)() noexcept;

由于 N4140 [except.spec]/2:

An exception-specification shall not appear in a typedef declaration or alias-declaration.

所以我假设问题是针对 C++1z 的,其中异常规范是类型系统的一部分。


[conv.fctptr]/1 :

A prvalue of type “pointer to noexcept function” can be converted to a prvalue of type “pointer to function”. The result is a pointer to the function.

因此,void (*)() noexcept 可以(隐式)转换为 void (*)()

[expr.static.cast]/7 :

The inverse of any standard conversion sequence (Clause [conv]) not containing a [(various other cases omitted)] function pointer ([conv.fctptr]) conversion, can be performed explicitly using static_cast.

[expr.static.cast] 中的其他任何内容都不允许将 void (*)() 转换为 void (*)() noexcept,因此这不是一个可以由 static_cast 执行的转换。

[expr.reinterpret.cast]/6 :

A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified. [ Note: see also [conv.ptr] for more details of pointer conversions. — end note ]

所以reinterpret_cast可以执行这个转换。

由于 fp2_type(fp) 等价于 C 风格的转换 (fp2_type) fp ( [expr.type.conv]/1 ),并且 since C-style casts do a reinterpret_cast when static_cast is not possible (为简单起见忽略 const_cast,因为它与此处无关),fp2_type(fp) 是一个格式正确的 reinterpret_cast。然而,这种类型转换的结果不能使用,只能将其转换回去。

关于c++ - 将函数指针转换为 noexcept 指定的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35551197/

相关文章:

c++ - 放置 new 加析构函数和简单的值初始化 noexcept 语义

c++ - 在 decltype() 或 operator noexcept() 上下文中对 nullptr 使用 placement new

c++ - 检测函数类型是否为 noexcept 的特征

c++ - 在 DLL 中导出的 C++ 函数中使用 #ifdef block

c++ - 为什么在将数据从文本文件移动到数组时无法获得正确的输出

c++ - 运行时检查失败 #0 从 kernel32.dll 加载 QueryFullProcessImageName

c - 提供函数指针时取消引用指向不完整类型的指针

C++ "Importing"来自另一个 C++ 文件的枚举类

c++ - 如何通过删除 "free faces"从非流形中提取底层 2-流形?

c++ - 函数指针将参数强制转换为 void