Skip to content

Instantly share code, notes, and snippets.

@oliora
Last active May 24, 2022 03:01
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliora/928424f7675d58fadf49c70fdba70d2f to your computer and use it in GitHub Desktop.
Save oliora/928424f7675d58fadf49c70fdba70d2f to your computer and use it in GitHub Desktop.
constexpr_assert
// A compilation of the following posts:
// http://stackoverflow.com/questions/18648069/g-doesnt-compile-constexpr-function-with-assert-in-it
// http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
#include <cassert>
#include <utility>
template<class Assert>
inline void constexpr_assert_failed(Assert&& a) noexcept { std::forward<Assert>(a)(); }
// When evaluated at compile time emits a compilation error if condition is not true.
// Invokes the standard assert at run time.
#define constexpr_assert(cond) \
((void)((cond) ? 0 : (constexpr_assert_failed([](){ assert(!#cond);}), 0)))
/////////////////////////////////////////////////////////////////////
// Usage example:
inline constexpr int divide(int x, int y) noexcept
{
return constexpr_assert(x % y == 0), x / y;
}
int main()
{
constexpr auto a = divide(6, 2); // OK
constexpr auto b = divide(5, 2); // Compile time error in both debug and release builds
auto a1 = divide(6, 2); // OK
auto a2 = divide(5, 2); // Run time assertion (debug build only)
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment