Offset from member pointer without temporary instance

后端 未结 3 729
故里飘歌
故里飘歌 2021-02-05 22:21

I would like to get the offset of a standard layout member variable when provided with a poiner to that variable. I cannot use offsetof since I have a pointer and n

3条回答
  •  后悔当初
    2021-02-05 23:03

    So how about:

    template
    struct {
        ptrdiff_t get_offset( int (T::*mem) )
        {
            return 
            ( &reinterpret_cast( 
                reinterpret_cast( 1 )->*mem ) 
              - reinterpret_cast( 1 )      );
        }
    };
    

    ..?

    This avoids both using a dummy AND dereferencing null. It works on all the compilers I've tried. The cast to char reference and then take the address (rather than take the address and then cast to char pointer) may seem unusual but it avoids a warning/error on some compilers.

提交回复
热议问题