How to implement an own assert function (or macro) that uses static_assert
in the constexpr case. The following naive approach fails:
void constexpr ownAssert( bool assumption )
{
if ( assumption )
return;
if ( std::is_constant_evaluated())
static_assert( assumption );
else
printf("Assertion failed.\n");
}
for the use in e.g.
constexpr int calulate( int i)
{
ownAssert( i > 0 ); // must be greater 0
assert( i > 0 ); // works
/* ... */
}
throw
should not be used for the implementation as the code is used with exceptions disabled.
Using the fact that calling a non-constexpr function in a constant evaluated context will result in a compile-time error the solution is straightforward:
#define OWN_ASSERT( assertion ) do { \
if ( assertion ) break; \
printf("ASSERTION failed: '%s'", # assertion); \
} while(false)