The answer is that not all operations in a compile-time routine have to be constexpr; only the ones that are executed at compile time.
In the example above, the operations are:
hours t = duration_cast<hours>(d);
if (t > d) {} // which is false, so execution skips the block
return t;
all of which can be done at compile time.
If, on the other hand, you were to try:
static_assert(floor<hours>(minutes{-3}).count() == -1, "”);
it would give a compile-time error saying (using clang):
error: static_assert expression is not an integral constant expression
static_assert(floor<hours>(minutes{-3}).count() == -1, "");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: non-constexpr function 'operator--' cannot be used in a constant expression
--t;
^
note: in call to 'floor(minutes{-3})'
static_assert(floor<hours>(minutes{-3}).count() == -1, "");
When writing constexpr code, you have to consider all the paths through the code.
P.S. You can fix the proposed floor
routine thusly:
template <class To, class Rep, class Period,
class = enable_if_t<detail::is_duration<To>{}>>
constexpr
To floor(const duration<Rep, Period>& d)
{
To t = duration_cast<To>(d);
if (t > d)
t = t - To{1};
return t;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…