0

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)
hpc64
  • 35
  • 5
  • "*throw should not be used for the implementation as the code is used with exceptions disabled.*" Just because you've disabled exceptions doesn't mean you can't have a `throw` statement. You just shouldn't execute it at runtime. – Nicol Bolas Aug 20 '22 at 15:28
  • @NicolBolas gcc and clang both disagree. – n. m. could be an AI Aug 20 '22 at 15:39
  • 4
    It doesn't seem possible. `static_assert` requires a constant expression. A function parameter and anything that depends on one is never a constant expression. – n. m. could be an AI Aug 20 '22 at 15:54

0 Answers0