Determining struct member byte-offsets at compile-time?

£可爱£侵袭症+ 提交于 2019-11-29 06:39:01

offsetof is a compile time constant, if we look at the draft C++ standard section C.3 C standard library paragraph 2 says:

The C++ standard library provides 57 standard macros from the C library, as shown in Table 149.

and the table includes offsetof. If we go to the C99 draft standard section 7.17 Common definitions paragraph 3 includes:

offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes [...]

In C:

offsetof is usually actually a macro, and due to its definition, it will probably optimized by the compiler so that it reduces to a constant value. And even if it does become an expression, it is small enough that it should cause almost no overhead.

For example, at the file stddef.h, it is defined as:

#define offsetof(st, m) ((size_t)(&((st *)0)->m))

In C++:

Things get a bit more complicated, since it must resolve offsets for members as methods and other variables. So offsetof is defined as a macro to call another method:

#define offsetof(st, m) __builtin_offsetof(st, m)

If you need it only for structs, you are good enough with offsetof. Else, I don't think it is possible.

Brandon

Are you sure it is run-time?

The following works..

#include <iostream>
#include <algorithm>


struct vertex_t
{
    int32_t position;
    int32_t normal;
    int32_t texcoord;
};

const int i = offsetof(vertex_t, normal); //compile time..

int main()
{
    std::cout<<i;
}

Also see here: offsetof at compile time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!