简体   繁体   中英

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++?

You cannot cast a function pointer to void* with static_cast , but you may be able to do so with 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. (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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