Bitesize Modern C++ : static_assert

C’s assert library is a useful tool for catching invalid invariants (conditions that must hold true in order for your system to operate as specified) in your program. The big problem with assert is that it’s a run-time check; in many cases the best you can do  to recover from an assert failure is restart the system or put it into a quiescent state.

In a lot of cases the (faulty) invariants could be detected at compile-time but in C++98 there was no mechanism for doing so. The pre-processor has an assert-like mechanism – #error – but the pre-processor has no knowledge of your C++ code so it cannot evaluate program invariants.

In C++11 a compile-time assert mechanism was added: static_assert.

static_assert acts like run-time assert except that the checked-condition must be a constant-expression (that is, an expression that can be evaluated at compile-time); the checked-condition must be a boolean expression, or an expression that can be converted to a boolean.

image

The message string must be a string literal.  It cannot be a (compile-time) computed value (ignoring pre-processor stringification).

From C++17 the message will be optional.

 

More information

Can’t wait? Download the full set of articles as a PDF, here.

To learn more about Feabhas’ Modern C++ training courses, click here.

Glennan Carnie
Dislike (0)
Website | + posts

Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.

About Glennan Carnie

Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry. He specialises in C++, UML, software modelling, Systems Engineering and process development.
This entry was posted in C/C++ Programming and tagged , , , , , . Bookmark the permalink.

2 Responses to Bitesize Modern C++ : static_assert

  1. Michael Price says:

    One correction: the message string must be a string-literal according to C++11, C++14, and the current C++17 draft.

    There is a proposal (N4433 to allow it to be a constant-expression that evaluates to a constant C-string type (const char*, const wchar_t*, etc...)

    Like (0)
    Dislike (0)

  2. Quite right. I've amended the article to reflect this.

    Thanks!

    Like (0)
    Dislike (0)

Leave a Reply