计算结构类型成员的偏移量,以前在ANSI C标准源码中看到过类似的实现,突然想起来就写了个demo记录下。
1 /**
2 * Copyright 2010 Lei Hu. All rights reserved.
3 * Lei Hu PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4 */
5 #pragma pack(push)
6 #pragma pack(4)
7
8 /**
9 * Get the offset of given type of member.
10 * @param TYPE The type name.
11 * @param MEMBER The member name.
12 * @return The offset value.
13 */
14 #define OFFSETOF(TYPE, MEMBER) reinterpret_cast<size_t> (&(reinterpret_cast<char &>(reinterpret_cast<TYPE *>(0)->MEMBER)))
15
16 #include <iostream>
17 using namespace std;
18
19
20 typedef struct A
21 {
22 char a;
23 double b;
24 int c;
25 }A;
26
27 void main()
28 {
29 cout << OFFSETOF(A, b) << endl;
30 }
31
32
33 #pragma pack(pop)