[cppx] Compile time assertions (static asserts)

Sometimes you want to assert at compile time. E.g., you might want to assert that type double is IEEE-754, using std::numeric_limits, except that that’s pretty dangerous since the g++ compiler reports that it’s IEEE-754 even when it’s been instructed to emit fast, non-IEEE-754-conforming code. But e.g. in the cppx library code there are compile time asserts, static asserts, like CPPX_STATIC_ASSERT( CPPX_IS( DerivedAndBase, Derived, Base ) ).

The cppx library’s static assert, a macro CPPX_STATIC_ASSERT, is utterly simple:

In [progrock/cppx/devsupport/static_assert.h]:

#define CPPX_STATIC_ASSERT( e ) \
    typedef char CppxStaticAssertShouldBeTrue[(e)? 1 : -1]

// The following macro is mainly comment-like, but performs such checking as it can.
#define CPPX_IS_OVERRIDE_OF( memberSpec, args ) \
    ::progrock::cppx::devsupport::suppressUnusedWarning( sizeof( (memberSpec args, 0) ) )

A static assert failure cannot be ignored. So when a static assert fails you have to look at that place in the code. And that tells you what the assert was about.

The CPPX_IS_OVERRIDE_OF macro is a special kind of static assert that does not guarantee to fail, but that generally catches a failure to actually override a method. I’ve found that it helps to have CPPX_IS_OVERRIDE_OF macro calls as in-source documentation. And the checking that it does can’t hurt.

Using this macro does however require that the overridden base class method is accessible, which generally means using protected instead of private for virtual methods (it’s just a matter of trusting derived classes).


One comment on “[cppx] Compile time assertions (static asserts)

  1. Pingback: Hubris, significant spaces, g++ | Alf on programming (mostly C++)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s