Using static asserts
A static assert is the main language feature for implementing custom compile-time checks. It can check any condition. If the static assert is compiled, the condition must be true; otherwise, it will issue a compile-time error. Here, we'll use it to verify whether our struct is of the correct size to interface with hardware.
How to do it…
Perform the following steps:
Write
static assert(condition, message);
in the code.If your condition is too complex to represent as a simple condition, you may write a helper function and call it for the condition.
Remember that static assert must pass if the code is compiled, even if the path is not actually executed.
The code is as follows:
align(1) struct IDTLocation { align(1): ushort length; uint offset; } static assert(IDTLocation.sizeof == 6, "An IDTLocation must be exactly six bytes with no padding.");
How it works…
The compile-time partner to assert
is static assert
. It functions in the same way, but instead of checking a runtime...