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 Compile-Time Assertion Reviewed by Sourabh Soni on Thursday, February 04, 2010 Rating: 5

No comments

Author Details

Image Link [https://3.bp.blogspot.com/-zo21XIdyPqc/VuTrFfUyPhI/AAAAAAAAAO8/EEWTN73XHUA7aTIjuxuBSN-WGaGkNUymA/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]