|
Archives
D Programming
DD.gnu digitalmars.D digitalmars.D.bugs digitalmars.D.dtl digitalmars.D.dwt digitalmars.D.announce digitalmars.D.learn digitalmars.D.debugger C/C++ Programming
c++c++.announce c++.atl c++.beta c++.chat c++.command-line c++.dos c++.dos.16-bits c++.dos.32-bits c++.idde c++.mfc c++.rtl c++.stl c++.stl.hp c++.stl.port c++.stl.sgi c++.stlsoft c++.windows c++.windows.16-bits c++.windows.32-bits c++.wxwindows digitalmars.empire digitalmars.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
#ifndef BUILD_ASSERT
#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
|