【问题标题】:What is a safe, cross-platform way to perform range checks before casting to a smaller numeric type?在转换为较小的数字类型之前执行范围检查的安全、跨平台方法是什么?
【发布时间】:2017-02-10 02:34:33
【问题描述】:

Here 是我能找到的最接近的副本。

尽管有标签,但问题似乎与 C 有关,可用的 answer 引用了 C99 规范。

在不使用 Boost 或其他库的情况下,在 C++98 中处理此检查的正确方法是什么?

【问题讨论】:

标签: c++ casting c++98 range-checking


【解决方案1】:

您可以从gsl::narrow() 复制代码并稍作调整,将其转换为can_narrow(),返回bool 而不是throwing:

// narrow_cast(): a searchable way to do narrowing casts of values
template<class T, class U>
inline constexpr T narrow_cast(U u) noexcept
{ return static_cast<T>(u); }

namespace details
{
    template<class T, class U>
    struct is_same_signedness : public std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value>
    {};
}

template<class T, class U>
inline bool can_narrow(U u)
{
    T t = narrow_cast<T>(u);
    if (static_cast<U>(t) != u)
        return false;
    if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
        return false;
    return true;
}

【讨论】:

  • 在我看来 can_narrow(2.0001) 会返回 false,不是吗?
  • “范围检查”是一个特定值是否可以安全地缩减为目标类型的问题,而不是源类型范围是否超出目标类型范围的问题。只要u(std::numeric_limits::lowest&lt;T&gt;(), std::numeric_limits::max&lt;T&gt;())之内,范围检查不应该返回true吗?
猜你喜欢
  • 2017-06-15
  • 1970-01-01
  • 2018-02-18
  • 2011-01-09
  • 2014-10-05
  • 2021-09-14
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多