Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
302 views
Welcome To Ask or Share your Answers For Others

1 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...