C++ Foot gun with a timer

Do not use static_assert to constrain the types you are developing. Huh?  What that even means? Why not?

Currently using std:: well-known containers, to the surprise of many, one can create all sorts of fake types, and then someone else unknowingly and innocently might code all sorts of well-hidden timebombs, using those fake types. We call them “timebombs”, because they might be unnoticed for months or even years and just then make your code not compile. Godbolt is here.

static_assert does not constrain the creation of type, it does constrain the instantiation of a type. Consider this example from one good and young c++ author.

timebomb_type is a fake (aka illegal) type. No instances of that type can be ever made. Any attempt to do so will be stopped by the compiler. Exactly the same fake “constraint” is adopted in (for example) MS STL.

The key issue is that type (timebomb_type) can be used to create other types. That is because static_assert will “kick in” just when someone tries to instantiate the type. Not before.

There is more. Template instantiation anyone? We have that too.

Imagination is the only constrain (pun intended) there. All sorts of well-hidden timebombs and foot guns can be produced in standard C++ with no or very little warning from the compiler. And no warning to the future unfortunate users. Perhaps you want to try it yourself in the Godbolt.

The simple remedy

Just a forward declared type constrained template is enough to stop wrong type definitions. And you usually constrain the type with std::enable_if.

The outcome is, the user (or you) can not introduce types whose usage will not compile only a few months or years down the line.

This peculiarity is what one might describe as “C++ foot gun with a timer” …


Using C++20 and beyond, one can use the dreaded constraints, everybody is afraid of. Here is one example  to try and convince you to look into the C++20  requires keyword:

Not that complicated. It looks quite clear actually.  If you try and create a “wrong” type from that template you will get much clearer error messages vs using the good old std::enable_if.

Is that one big foot gun?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: