Offset from member pointer without temporary instance

后端 未结 3 737
故里飘歌
故里飘歌 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:11

    How about:

    template
    struct {
      ptrdiff_t get_offset( int (T::*mem) )
      {
        union {
          int used;
          T unused;
        } dummy;
        return reinterpret_cast(&(dummy.unused.*mem)) 
          - reinterpret_cast(&dummy.unused);
      }
    };
    

    The address of a union member doesn't depend on the union member being constructed. Works already in C++03, but then only for PODs.

提交回复
热议问题