制作和使用std::chrono::duration
是否合法的包含值是无穷大,像这样吗?
std::chrono::duration{ std::numeric_limits::infinity() };
它会表现得“像我预期的那样”,在与其他持续时间相加或相减时保持无限值吗?
我已经研究了 cppreference,但我发现讨论这个问题的唯一内容是 duration_cast
上的页面注意到:
Casting from a floating-point duration to an integer duration is subject to undefined behavior when the floating-point value is NaN, infinity, or too large to be representable by the target's integer type. Otherwise, casting to an integer duration is subject to truncation as with any static_cast to an integer type.
这似乎暗示它是合法的,但只是以一种反手的方式。
(我使用类型来表示“请在 X 秒内唤醒我”的方式,正无穷大是一个有用的标记来表示“我真的不在乎我什么时候醒来”)
giá trị infinity
vì std::chrono::duration
算术运算符的行为将与您预期的一样。
std::chrono::duration
完全没问题
[time.duration]sự định nghĩa Rep
上存在的条件对于 template std::chrono::duration
Và gấp đôi
被明确允许(根据 [time.duration]/2 ),没有不允许的特殊值:
Rep
shall be an arithmetic type or a class emulating an arithmetic type.
std::numeric_limits::infinity()
完全没问题
[time.duration.arithmetic]Và [time.duration.nonmemberdefine]hiện hữu khoảng thời gian
上定义算术运算符的行为.对于每个 operator♦
并给出两个 khoảng thời gian
sự vật MỘT
Và B
持gấp đôi
giá trị Một
Và b
, A♦B
效果为 a♦b
将。例如 +
:
In the function descriptions that follow, CD
represents the return type of the function. CR(A, B)
represents common_type_t
.
template
constexpr common_type_t<>, duration>
operator+(const duration& lhs, const duration& rhs);
Trả về: CD(CD(lhs).count() + CD(rhs).count())
.
这明确意味着以下将按预期运行:
const double infinity = std::numeric_limits::infinity();
std::chrono::duration inf{ infinity };
std::chrono::duration one{ 1.0 };
inf + one; // as if std::chrono::duration{ infinity + 1.0 };
Tôi là một lập trình viên xuất sắc, rất giỏi!