在转换为较小的数值类型之前执行范围检查的安全、跨平台方法是什么
What is a safe, cross-platform way to perform range checks before casting to a smaller numeric type?
这是我能找到的最接近的副本。
尽管有标签,但问题似乎是关于 C 的,可用的答案引用了 C99 规范。
在 C++98 中处理此检查的正确方法是什么,而无需使用 Boost 或其他库?
您可以从gsl::narrow()
复制代码并稍微调整它,将其转换为返回bool
can_narrow()
而不是throw
:
// 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;
}
相关文章:
- 如何在Windows上检查EXE是否具有/GS安全保护
- 有没有一种简单的方法来检查C++中的不安全表达式
- 初始化期间针对安全检查的指针的恒定正确性
- 确保静态布尔检查的线程安全
- 如何安全,便便输入并检查重音字符
- 在转换为较小的数值类型之前执行范围检查的安全、跨平台方法是什么
- 是否有任何类型安全的、编译时检查的 printf 的实现
- 检查指针是否为null,然后在同一if语句中取消引用它,这样安全吗
- NULL指针检查线程安全
- C++11:对延迟初始化进行安全的双重检查锁定.可能的
- 这是否可以兑换线程安全的双重检查锁定模式
- 期货是检查单个线程完成情况的安全方法吗
- 在OpenCV 3.1.0 x64 (VS12)中使用TAPI时的BSOD(内核安全检查失败)
- 线程安全惰性初始化:静态vs std::call_once vs双重检查锁定
- 当数组出界时,是否通过异常安全检查
- TCP套接字安全吗?还是我应该总是检查用户
- 如何在cppcheck或clang中检查类型安全
- 安全,检查后强制转换为c++基类,不需要额外的行
- 对可能不完整的类型进行可选的安全检查强制转换
- 程序来检查我的wifi是否安全(即WPA2/WEP)在windows c++