I have several brief constexpr functions in my libraries that perform some simple calculations. I use them both in run-time and compile-time contexts.
I
A refinement on Daniel Frey's answer is to use noexcept on the constexpr function to turn the runtime error into a call to std::terminate. Assertion failures are unrecoverable; they should halt the process immediately. Turning them into exceptions is a very bad idea.
#include
#include
struct assert_failure
: std::logic_error
{
explicit assert_failure(const char *sz)
: std::logic_error(sz)
{}
};
constexpr bool in_range(int i, int j, int k) noexcept
{
return (i <= j && j <= k) ? true : throw assert_failure("input not in range");
}
int main(int argc, char* argv[])
{
constexpr bool b1 = in_range(0, 4, 5); // OK!
constexpr bool b2 = in_range(0, 6, 5); // Compile-time error!
bool b3 = in_range(0, 4, argc); // May or may not terminate the process
}
The runtime error for me looks like:
terminate called after throwing an instance of 'assert_failure'
what(): input not in range
Aborted (core dumped)
Hope that helps.