Offset from member pointer without temporary instance

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

    I'm afraid that no standard-compliant solution which satisfies OP requirements exists.

    I can give a couple of non-compliant ones.

    template
      size_t get_offset( int (T::*mem) )
        {
        return reinterpret_cast(&(((T*)nullptr)->*mem))-reinterpret_cast(nullptr);
        }
    

    It's funny, but the following works in VC2010, making use of offsetof being a macro.

    template
      size_t get_offset( int (T::*mem) )
        {
        return offsetof(T, *mem);
        }
    

提交回复
热议问题