用一种简单的方式,我能想到的最好的办法就是检查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();
}
}
本文链接:https://www.f2er.com/3152642.html