Can you write a static assert to check for data element offsets?

Given the following structure:

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

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

+6
source share
2 answers

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

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

This offsetof macro results in a constant expression; you can use a static statement to create a translation error if the condition is not met.

+3
source

Offsetof

You can use Offsetof marco contributed by the cstddef library. Here I get the offset first, then I use the operator of the simulation module to check if it is a multiple of 8. Then, if the remainder is 0, the offset is really a multiple of 8 bytes.

 // Offset.cpp #include <iostream> #include <string> #include <cstddef> #include <stdarg.h> struct ExampleStruct { char firstMember[8]; uint64_t secondMember; }; int main() { size_t offset = offsetof(ExampleStruct, secondMember); if(offset%8==0) std::cout << "Offset is a multiple of 8 bytes"; } 

Demo here

Offsetof with static_assert

Or in the context of this question, the goal is to have static_assert . Well, it's almost the same:

 // OffsetAssert.cpp #include <iostream> #include <string> #include <cstddef> #include <stdarg.h> struct ExampleStruct { char firstMember[8]; uint64_t secondMember; }; int main() { size_t offset = offsetof(ExampleStruct, secondMember); // Get Offset static_assert(offsetof(ExampleStruct, secondMember)%8==0,"Not Aligned 8 Bytes"); // Check if the offset modulus 8 is remainer 0 , if so it is a multiple of 8 std::cout << "Aligned 8 Bytes" << std::endl; // If Assert Passes it is aligned 8 bytes } 

Demo here

Type of use

I use the type std::size_t , because the type that you usually use to store the sizes of variables, objects, etc. And also because it expands to the expression std::size_t according to cppreference.com:

The Offsetof macro expands to an integer constant expression of the type std::size_t , whose value is the offset in bytes from the beginning of the object of the specified type to its specified member, including the addition, if any.

References

cpprefrence

cplusplus

+6
source

All Articles