As mentioned in one of my previous articles, a programmer should often use asserts to detect errors and bugs early. The problem with assertions is, that if you run your code, and the lines are not executed you’ll never get noticed about the problem.

In C++ you can use templates to detect errors during compile time.

A very simple template with one specialisation will take care of it:

template <bool> struct STATIC_ASSERT;
template <> struct STATIC_ASSERT<true> {};

The following lines will compile without problems:

int x = 3;
STATIC_ASSERT<x == 3>();

But the following ones will produce an error when we try to compile the code:

int x = 3;
STATIC_ASSERT<x == 4>();

This technique is very useful to detect bugs and problems very early and you should use it whenever possible instead of a regular assert.

The Boost library takes this concept a little bit further and includes workarounds for most compilers.

  1. Seanba (2011-01-29 08:40)

    Putting the boolean expression between angle brackets can be a bit awkward, as is the opening and closing parentheses that construct the STATIC_ASSERT object (note that you will compile fine if you accidently leave them off – even if the template argument is false).int x = 3;STATIC_ASSERT<x == 4>; // Oops – still compilesSo this might be a good use for a marco:#define static_assert(expr) STATIC_ASSERT<static_cast(expr)>()Usage:int x = 3;static_assert(x == 4); // fails to compile, as expected

  2. Seanba (2011-01-29 08:42)

    Dang, my posts above are not complete because the angle brackets are being treated as HTML code. If you can fix them up and remove one of them that’d be cool.

  3. joe (2011-01-29 08:49)

    damn wordpress. i just fixed this, so its possible to put code in the comments :-)did you mean:STATIC_ASSERT<x == 4>;this doesn’t compile in xcode. but yeah, a macro is a good idea, anyway.

  4. Seanba (2011-01-29 09:10)

    Yeah, that’s what I meant, with the trailing semi-colon, of course.

  5. joe (2011-01-29 09:48)

    ah, yes, of course. i fixed it!

  6. TH (2011-02-19 01:21)

    C++0x include “static_assert(condition,error_msg)” as a language builtin. You can future proof your code by making the macro take the same arguments and then be ready when you upgrade your compiler.

  7. joe (2011-02-19 01:26)

    Yes, that sounds like a very good idea.

Add your comment now