积分转换的运行时检查

假设使用以下功能:

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链-但是我想念一些更简单或更直接的方法吗?)

heminminzjl 回答:积分转换的运行时检查

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

大家都在问