www.digitalmars.com         C & C++   DMDScript  

c++ - build-time assert for DMC++

After struggling with other methods for effecting
a compile-time assert facility, I saw how the
boost library does it.  Their technique does not
quite work on DMC++ either, but a similar one does.
Here is the content of a header which will allow
compile-time constant expressions to be evaluated
and fail the build if their value comes up false
or 0:

// Build-time assert facility


#define BUILD_ASSERT( B ) typedef int \
 BUILD_ASSERT[ sizeof(BUILD_ASSERT_CHECK< static_cast<bool>( B ) >) ]

template <bool x> struct BUILD_ASSERT_CHECK;

template <> struct BUILD_ASSERT_CHECK<true> {};

#endif // BUILD_ASSERT

There is one remaining non-critical problem.  If
there are multiple uses of BUILD_ASSERT in one
translation unit, and some fail but others don't,
there will be more complaints from the compiler
than there are failed assertions.  I would have
excluded this, but the compiler's preprocessor
is (defectively) unable to incorporate the
__LINE__ macro into a token-pasted identifier.

Usage is pretty simple.  Example:

#include "build_assert.h"

struct Goober {
  char notpad;
  double number;

// If this fails, alignment must have changed.
BUILD_ASSERT(sizeof(Goober) == 12);

Note that the assertion failure is somewhat
cryptic, making it a good idea to comment
the assertion.

-Larry Brasfield
(address munged, s/sn/h/ to reply)
Oct 11 2002