这段代码如何成为constexpr? (std :: chrono) [英] How can this code be constexpr? (std::chrono)
问题描述
Howard Hinnant在标准论文P0092R1中写道:
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;
}
此代码如何工作?问题是 std :: chrono :: duration
上的操作符-
不是constexpr操作。定义为:
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, "");
这是怎么回事?
推荐答案
答案是,并非编译时例程中的所有操作都必须是constexpr;只有那些在编译时执行的操作。
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, "");
它会给出一个编译时错误,说(使用clang):
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, "");
在编写constexpr代码时,必须考虑通过所有路径代码。
When writing constexpr code, you have to consider all the paths through the code.
PS您可以这样修改建议的 floor
例程:
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;
}
这篇关于这段代码如何成为constexpr? (std :: chrono)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!