简体   繁体   English

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

[英]Why is static_cast from int (*)(int) to void* not allowed in C++?

Please consider the following code:请考虑以下代码:

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

int main() {

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

    return 0;
}

As you can see here the code does not compile.正如您在此处看到的,代码无法编译。 Why is static_cast from int (*)(int) to void* not allowed in C++?为什么在 C++ 中不允许从int (*)(int)void* static_cast

You cannot cast a function pointer to void* with static_cast , but you may be able to do so with reinterpret_cast .您不能使用static_cast将函数指针static_castvoid* ,但您可以使用reinterpret_cast这样做。

This is conditionally-supported with implementation-defined semantics, except that casting back to the original function pointer type yields the same pointer value, so that it may be used again to call the function.这是由实现定义的语义有条件地支持的,除了转换回原始函数指针类型会产生相同的指针值,以便可以再次使用它来调用函数。

Probably you aren't allowed to do anything else with the void* obtained in such a way, but you will need to look at the compiler documentation to determine that.可能您不允许对以这种方式获得的void*做任何其他事情,但是您需要查看编译器文档以确定这一点。 (Compilers should document implementation-defined behavior, but it often isn't done well or at all.) (编译器应该记录实现定义的行为,但它通常做得不好或根本没有完成。)

Especially on POSIX systems and Windows this cast is always supported.特别是在 POSIX 系统和 Windows 上,始终支持此转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM