-1

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

尽管有标签,但问题似乎是关于 C 的,可用的答案引用了 C99 规范。

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

4

1 回答 1

1

您可以从中复制代码gsl::narrow()并稍作调整,将其转换为can_narrow()返回 abool而不是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;
}
于 2017-02-09T17:02:54.213 回答