I would like to perform a compile-time check on datatype sizes in a C/C++ project, and error on unexpected mismatches. Simple
#if sizeof foo_t != sizeof bar_t
does not compile – claims that sizeof is not a proper compile-time constant.
The desired scope of platforms – at the very least Visual C++ with Win32/64, and GCC on x86/amd64.
EDIT: compile-time, not necessarily preprocessor. Just not a run-time error.
EDIT2: the code assumes that wchar_t is 2 bytes. I want a compilation error if it’s accidentally compiled with 4-byte wchar’s.
You have two options:
a) static_assert of C++11
b) BOOST_STATIC_ASSERT of boost
I would prefer the first one.
Edit:
The preprocessor is not really part of the language, as the name says it pre-processes a file, it has no knowledge of the language, so it does not know
sizeof.You could use some template to do some compile time code generation, for example: