积分转换的运行时检查

And*_*zos 6 c++ c++17

假设下面的函数:

template<typename T, typename U>
bool IsRepresentable(U u);
Run Code Online (Sandbox Code Playgroud)

TU在非布尔整数类型。

如果整数值u是表示的TIsRepresentable应该返回true,否则就应该返回false

IsRepresentable在C ++ 17中实现的最佳方法是什么?(或者标准库中是否存在现有的类似功能?)

(我现在的想法是一个constexpr的if-else链围绕std::is_signed/ sizeof/ std::numeric_limits- ?但我错过了一些更容易或更简单的方法)

max*_*x66 3

我能想象的最好的方法是,以简单的方式检查和的T(u) == u符号是否相同uT(u)

我的意思是

template <typename T, typename U>
bool IsRepresentable (U const & u)
 { return (T(u) == u) && (T(u) > T(0)) == (u > U(0)); }
Run Code Online (Sandbox Code Playgroud)