c++ - clang 认为我需要指向 "const function"吗?

标签 c++ function-pointers clang++ reinterpret-cast const-correctness

GodBolt
考虑以下代码片段:

using A = void(*)(int);

A foo(const void* ptr) 
{
    return reinterpret_cast<A>(ptr);
}
GCC 10 喜欢这个就好了。但是,clang++-10 说这是一个错误!
<source>:5:12: error: reinterpret_cast from 'const void *' to 'A' (aka 'void
 (*)(int)') casts away qualifiers

    return reinterpret_cast<A>(ptr);

           ^~~~~~~~~~~~~~~~~~~~~~~~
函数在 C++(和 C)中是不可变的,并且没有“const 函数”。那么为什么 clang++ 在这里提示呢?

最佳答案

因为标准是这么说的。
[expr.reinterpret.cast]/2:

The reinterpret_­cast operator shall not cast away constness.


[expr.const.cast]/7:

A conversion from a type T1 to a type T2 casts away constness if T1 and T2 are different, there is a cv-decomposition of T1 yielding n such that T2 has a cv-decomposition of the form CV-decomposition of T2

and there is no qualification conversion that converts T1 to CV-decomposition of T1


这里 T1 是 const void* , T2 是 void (*)(int) , n = 1, T2 的 cv 分解有 cv0 = "", P0 = "pointer to", cv1 = "", U2 = void(int) ,所以对应版本T1void* .没有来自 const void* 的资格转换至 void* .因此,转换抛弃了常量性并且不能由 reinterpret_cast 执行。 .

关于c++ - clang 认为我需要指向 "const function"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62961212/

相关文章:

c++ - 如何在函数模板的显式特化中推导模板参数?

c++ - 帮助提升绑定(bind)/功能

c - 将函数指针设置为静态地址

c++ - C++ 中的单元测试和测试代码覆盖率

c++ - 未解析的外部符号错误,即使函数存在 char*

android - .so 文件创建期间的链接器错误。错误 : Function not Implemented

c++ - Boost Log - 为什么不编译?

c++11 - 为什么 clang++ 缺少转发列表?

c++ - 为什么对象的静态初始化肯定为零?

c - 如何使用指针在 C 中的第一个空格上分割字符串?