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 would like to perform some assertions in the body of these functions, however assert(...)
is not valid in a constexpr
function and static_assert(...)
can not be used to check function parameters.
Example:
constexpr int getClamped(int mValue, int mMin, int mMax) noexcept
{
assert(mMin <= mMax); // does not compile!
return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}
Is there a way to check whether the function is being executed in a run-time or compile-time constant and execute the assert
only if it's being executed at run-time?
constexpr int getClamped(int mValue, int mMin, int mMax) noexcept
{
assert_if_runtime(mMin <= mMax);
return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…