Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

c++ - How can this code be constexpr? (std::chrono)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...