In the standards paper P0092R1, Howard Hinnant wrote:
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;
return t;
}
How can this code work? The problem is that operator--
on a std::chrono::duration
is not a constexpr operation. It is defined as:
duration& operator--();
And yet this code compiles, and gives the right answer at compile time:
static_assert(floor<hours>(minutes{3}).count() == 0, "”);
What's up with that?
Constexpr constructors are permitted for classes that aren't literal types. For example, the default constructor of std::unique_ptr is constexpr, allowing constant initialization.
constexpr std::string While it's best to rely on string_views and not create unnecessary string copies, the example above shows that you can even create pass vectors of strings inside a constexpr function!
std::min and std::max are constexpr in C++14, which obviously means there isn't a good reason (these days) not to have them constexpr. Problem solved :-) Save this answer.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With