Compile time sizeof / alignof

Manually adding up member sizes or figuring out alignment is for chumps! And compilers. Fortunately you can avoid being a chump by abusing your compiler to make it print the sizeof() in a compilation error.

You: template<int> class X; X<sizeof(SomeType)> _;

Compiler: ‘_’ uses undefined class ‘X<48>’

You: I’m so sorry, I totally thought that would compile.

Update

Visual Studio can show the result of sizeof-expressions by hovering over them (see reddit comments). The feature seems to rely on IntelliSense, which unfortunately is too slow for me to use. Additionally I often code in a stand-alone text editor and build from the command-line. Forcing a compilation error that tells you the size is IDE-independent and works on other compilers too.

Leave a Reply