Search code examples
c++structoffsetcompile-timeoffsetof

Determining struct member byte-offsets at compile-time?


I want to find the byte offset of a struct member at compile-time. For example:

struct vertex_t
{
    vec3_t position;
    vec3_t normal;
    vec2_t texcoord;
}

I would want to know that the byte offset to normal is (in this case it should be 12.)

I know that I could use offsetof, but that is a run-time function and I'd prefer not to use it.

Is what I'm trying to accomplish even possible?

EDIT: offsetof is compile-time, my bad!


Solution

  • 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 [...]