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
Throwing an exception might be useful as the compiler will ignore the run-time part when it knows at compile-time that the exception is not thrown.
#include
constexpr int getClamped(int mValue, int mMin, int mMax)
{
return ( mMin <= mMax ) ?
( mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue) ) :
throw "mMin must be less than or equal to mMax";
}
int main( int argc, char** argv )
{
// These two work:
static_assert( getClamped( 42, 0, 100 ) == 42, "CT" );
assert( getClamped( argc, 0, 100 ) == argc );
// Fails at compile-time:
// static_assert( getClamped( 42, 100, 0 ) == 42, "CT" );
// Fails at run-time:
// assert( getClamped( argc, 100, 0 ) == argc );
}
Live example