积分转换的运行时检查
Run-time check of integral conversion
假设在下面的函数中:
template<typename T, typename U>
bool IsRepresentable(U u);
T
和U
是非布尔积分类型。
如果u
的整数值可以用T
表示,那么IsRepresentable
应该返回true
,否则它应该返回false
。
在 C++17 中实施IsRepresentable
的最佳方法是什么?(或者标准库中是否有现有的类似函数?
(我目前的想法是围绕std::is_signed
/sizeof
/std::numeric_limits
的constexpr if-else链 - 但我是否错过了一些更简单或更直接的方法?
我能想象到的最好的,以一种简单的方式,就是检查T(u) == u
和u
和T(u)
的迹象是否相同
我的意思是
template <typename T, typename U>
bool IsRepresentable (U const & u)
{ return (T(u) == u) && (T(u) > T(0)) == (u > U(0)); }
作为接受答案的替代方案,我建议您使用 boost::numeric_cast。示例用法:
https://coliru.stacked-crooked.com/a/c39d5c9e7aed26ad
#include <boost/numeric/conversion/cast.hpp>
#include <iostream>
int main()
{
using boost::numeric_cast;
using boost::numeric::bad_numeric_cast;
using boost::numeric::positive_overflow;
using boost::numeric::negative_overflow;
try
{
int i=42;
short s=numeric_cast<short>(i); // This conversion succeeds (is in range)
}
catch(negative_overflow& e) {
std::cout << e.what();
}
catch(positive_overflow& e) {
std::cout << e.what();
}
try
{
int i=70000;
short s=numeric_cast<short>(i); // ad numeric conversion: positive overflow
}
catch(negative_overflow& e) {
std::cout << e.what();
}
catch(positive_overflow& e) {
std::cout << e.what();
}
}
相关文章:
- 在运行时检查继承是否只有一种类型和 void*
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 运行时检查失败 #0 用于运行时重新编译
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 运行时检查失败 #2 MSVC 仅使用 utf8proc 进行调试
- std::copy 导致运行时检查失败 #2
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- 积分转换的运行时检查
- 运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- 运行时检查失败 - 变量周围的堆栈已损坏
- swscanf_s - 运行时检查错误
- 动态强制转换的运行时检查
- 运行时检查实例 (Base*) 是否覆盖父函数 (Base::f())
- 如何在 Linux 运行时检查堆栈使用情况?
- 调试:运行时检查失败 #2 - 变量"LoggerThread"周围的堆栈已损坏
- 运行时检查失败 #2 - 变量周围的堆栈'k'已损坏
- 运行时检查失败 #2 - 变量"数字选择"周围的堆栈已损坏
- 可以在编译时或运行时检查STD ::对齐的限制
- 如何避免对编译后无法访问的正在运行的代码部分进行运行时检查?