为什么在 C++ 中不允许从 int (*)(int) 到 void* 的 static_cast ?

Blu*_*une 3 c++ casting void-pointers

请考虑以下代码:

int f(int i){return i*i;};

int main() {

    void* p = static_cast<void*>(&f);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如您在此处看到的,代码无法编译。为什么在 C++ 中不允许static_castint (*)(int)void*

wal*_*nut 5

您不能将函数指针强制转换为void*with static_cast,但您可以使用reinterpret_cast.

这是由实现定义的语义有条件地支持的,除了转换回原始函数指针类型会产生相同的指针值,以便可以再次使用它来调用函数。

可能您不允许对void*以这种方式获得的内容做任何其他事情,但是您需要查看编译器文档以确定这一点。(编译器应该记录实现定义的行为,但它通常做得不好或根本没有完成。)

特别是在 POSIX 系统和 Windows 上,始终支持此转换。