Why do function pointers all have the same value?

前端 未结 4 490
难免孤独
难免孤独 2021-01-23 05:30

For example:

using namespace std;
#include 

void funcOne() {
}

void funcTwo( int x ) {
}

int main() {

  void (*ptrOne)() = funcOne;
  cout &l         


        
4条回答
  •  迷失自我
    2021-01-23 05:55

    Function pointers do not implicitly convert to void *, which is what operator << overloads on.

    This is specified by omission in C++11 §4.10/2:

    A prvalue of type “pointer to cv T,” where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a “pointer to cv T” to a “pointer to cv void” points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject). The null pointer value is converted to the null pointer value of the destination type.

    Function types are not object types.

    Moreover, you can't even do it using static_cast. Functions and objects may live in completely different address spaces (this is called Harvard architecture), with differently-sized pointers. Converting a function pointer to void * can maybe be done with reinterpret_cast: it's "conditionally-supported" (C++11 §5.2.10/8). Such a void * should only be used for printing or conversion back to the original function pointer type.

提交回复
热议问题