Search code examples
c++assert

Can you write a static assert to verify the offset of data members?


Given the following struct:

struct ExampleStruct {
    char firstMember[8];
    uint64_t secondMember;
};

Is there a way to write a static assert to verify that the offset of secondMember is some multiple of 8 bytes?


Solution

  • If your type has standard layout, you can use the offsetof macro:

    #include <cstddef>
    
    static_assert(offsetof(ExampleStruct, secondMember) % 8 == 0, "Bad alignment");
    

    This the offsetof macro results in a constant expression, you can use a static assertion to produce a translation error if the condition is not met.