[c++] Static assertions – Part III

For completeness let’s look at the static_assert keyword introduced as part of C++0x. Picking up where the previous two posts (I & II) left off (in 2008!).

int main( ) {
    static_assert( false, "This must be true" );

    return 0;
}

Visual Studio 2010 outputs:
1>main.cpp(2): error C2338: This must be true

Hooray for progress!

A static assertion that outputs a user controlled error message. Making it much easier to indicate what the actual problem is, and avoiding the need to dig through large amounts of invalid and/or undefined type related compiler output mess.

Better yet; BOOST_STATIC_ASSERT will take advantage of static_assert if your compiler supports it.

#include <boost/static_assert.hpp>

#pragma pack( push, 1 )
struct PktData {
    char b1;
    char b2;
};
#pragma pack( pop )

BOOST_STATIC_ASSERT( 1 == sizeof(PktData) );

Visual Studio 2010 outputs:
1>main.cpp(10): error C2338: 1 == sizeof(PktData)

Where the error message is populated by the failing expression. Which may be nicer than having to specify your own error message as required by static_assert.