在学习 static_cast 和dynamic_cast 时,我看到了一条关于在将 double 类型转换为 int 类型时额外检查溢出和下溢的建议。我在这里该怎么做?
double value1{ 4.8967 };
int value2 = static_cast<int>(value1);
std::cout << value2 << std::endl;
我尝试到处搜索,结果发现算术上溢/下溢,但这里的情况似乎并非如此。我希望有几个链接可以让我更具体地了解它
std::numeric_limits
创建一个辅助函数来避免溢出。然后,如果存在下溢,您将获得最小可能的 int
值;如果存在上溢,您将获得最大可能的 int
值。
#include <iostream>
#include <limits> // numeric_limits
template <class R, class T>
R anti_overflow_clamp(T value) {
if (value <= std::numeric_limits<R>::lowest()) [[unlikely]]
return std::numeric_limits<R>::lowest();
if (std::numeric_limits<R>::max() <= value) [[unlikely]]
return std::numeric_limits<R>::max();
return static_cast<R>(value);
}
int main() {
double value1 = -9872034875209384574237698276453978264398576.0;
auto value2 = anti_overflow_clamp<int>(value1);
std::cout << value2 << '\n'; // min value for int
}