Compile-Time Assertion
In software programming, it is better to catch programming errors as earlier as possible in the stage. In general, detecting errors at program load-time is preferred over detecting the same at run-time. Furthermore, it is preferred to detect errors at compile-time than at the run-time.
“assert()” macro provides a way to catch errors at the run-time. However, it is possible to catch many of such errors at the compile-time. Here is the trick of compile-time assertion.
template<int> struct CompileTimeAssertion; // Define CompileTimeAssertion<true> only. // CompileTimeAssertion<false> remains undefined. template<> struct CompileTimeAssertion<true> {}; // Macro for developer-readable error messages. #define COMPILE_TIME_ASSERT(expr,msg) \ { \ CompileTimeAssertion<((expr) != 0)> ERROR_##msg; \ (void)ERROR_##msg; \ } |
Note that CompileTimeAssertion<true> specialization is defined and its object can be constructed whereas CompileTimeAssertion<false> is undefined and construction of object of the same would result into compile-time errors. Hence, when expr is compiled as false in COMPILE_TIME_ASSERT(expr,msg) programmer would see the compilation error due to no constructor definition for CompileTimeAssertion<false>. Here is an example usage.
// Safe reinterpret-cast // Give compile-time error – “UnSafeCastingToSmallerSize” when // sizeof(O) < sizeof(T) template<typename O, typename T> O* SafeReinterpretCast(T* iObj) { COMPILE_TIME_ASSERT(sizeof(O) >= sizeof(T), UnSafeCastingToSmallerSize); return reinterpret_cast<O>(iObj); } |
Compile-Time Assertion
Reviewed by Sourabh Soni
on
Thursday, February 04, 2010
Rating:
No comments