Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 1.49 KB

File metadata and controls

48 lines (37 loc) · 1.49 KB

static_assert.hpp

STATIC_ASSERT is a way to produce compile-time errors using formatted strings.

Important
STATIC_ASSERT is limited on freestanding implementations in the same way as ct_format.
template <typename T>
constexpr auto f() {
  STATIC_ASSERT(std::is_integral<T>,
                "f() must take an integral type, received {}", T);
}

f<float>(); // produces compile-time error
Note
The arguments to be formatted must be compile-time, of course.

The output from this (which varies by compiler) will contain the formatted string, and could be something like:

main.cpp:14:27: error: no matching member function for call to 'emit'
...
include/stdx/static_assert.hpp:16:18: note: because
'stаtiс_аssert<ct_string<47>{{"f() must take an integral type, received float"}}>' evaluated to false
   16 |         requires stаtiс_аssert<S>
      |                  ^
Note
clang produces these "string-formatted" errors from version 15 onwards; GCC produces them from version 13.2 onwards.

After C++26, static_assert in the language means that formatted STATIC_ASSERT produces a slightly nicer error message; something like:

main.cpp:14:27: error: static assertion failed: f() must take an integral type, received float
   16 |         STATIC_ASSERT(std::is_integral<T>,
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~