How to store various types of function pointers together?

前端 未结 4 556
滥情空心
滥情空心 2021-01-14 18:08

Normal pointers can be stored using a generic void*. e.g.

void* arr[10];
arr[0] = pChar;
arr[1] = pINt;
arr[2] = pA;

Sometime

4条回答
  •  庸人自扰
    2021-01-14 18:37

    A pointer to a function can be converted to a pointer to a function of a different type with a reinterpret_cast. If you convert it back to the original type you are guaranteed to get the original value back so you can then use it to call the function. (ISO/IEC 14882:2003 5.2.10 [expr.reinterpret.cast] / 6)

    You now only need to select an arbitrary function pointer type for your array. void(*)() is a common choice.

    E.g.

    int main()
    {
        int a( int, double );
        void b( const char * );
    
        void (*array[])() = { reinterpret_cast(a)
                            , reinterpret_cast(b) };
    
        int test = reinterpret_cast< int(*)( int, double) >( array[0] )( 5, 0.5 );
        reinterpret_cast< void(*)( const char* ) >( array[1] )( "Hello, world!" );
    }
    

    Naturally, you've lost a lot of type safety and you will have undefined behavior if you call a function through a pointer to a function of a different type.

提交回复
热议问题