积分转换的运行时检查

Run-time check of integral conversion

本文关键字:运行时 检查 转换      更新时间:2023-10-16

假设在下面的函数中:

template<typename T, typename U>
bool IsRepresentable(U u);

TU是非布尔积分类型。

如果u的整数值可以用T表示,那么IsRepresentable应该返回true,否则它应该返回false

在 C++17 中实施IsRepresentable的最佳方法是什么?(或者标准库中是否有现有的类似函数?

(我目前的想法是围绕std::is_signed/sizeof/std::numeric_limits的constexpr if-else链 - 但我是否错过了一些更简单或更直接的方法?

我能想象到的最好的,以一种简单的方式,就是检查T(u) == uuT(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();
}
}