【发布时间】:2017-02-10 02:34:33
【问题描述】:
Here 是我能找到的最接近的副本。
尽管有标签,但问题似乎与 C 有关,可用的 answer 引用了 C99 规范。
在不使用 Boost 或其他库的情况下,在 C++98 中处理此检查的正确方法是什么?
【问题讨论】:
标签: c++ casting c++98 range-checking
Here 是我能找到的最接近的副本。
尽管有标签,但问题似乎与 C 有关,可用的 answer 引用了 C99 规范。
在不使用 Boost 或其他库的情况下,在 C++98 中处理此检查的正确方法是什么?
【问题讨论】:
标签: c++ casting c++98 range-checking
您可以从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;
}
【讨论】:
u在(std::numeric_limits::lowest<T>(), std::numeric_limits::max<T>())之内,范围检查不应该返回true吗?