C++ 依赖于从任何数字类型(无符号,int,…)到double的隐式提升安全吗?

C++ 依赖于从任何数字类型(无符号,int,…)到double的隐式提升安全吗?,c++,double,unsigned-integer,C++,Double,Unsigned Integer,我有一个图形模板类,它为权重类型(可以是unsigned、int或double)接受一个参数。此外,为了比较double,我使用以下类型的内联函数: inline bool EpsLess(double x, double y, double epsilon = 1.e-10) { return x < y - epsilon; } inline bool EpsEqual(double x, double y, double epsilon = 1.e-10) { ret

我有一个图形模板类,它为权重类型(可以是unsigned、int或double)接受一个参数。此外,为了比较double,我使用以下类型的内联函数:

inline bool EpsLess(double x, double y, double epsilon = 1.e-10)
{
    return x < y - epsilon;
}
inline bool EpsEqual(double x, double y, double epsilon = 1.e-10)
{
    return !EpsLess(x,y) && !EpsLess(y,x);
}
inline bool EpsLess(双x,双y,双epsilon=1.e-10)
{
返回x
以下类中的比较器是否安全

template <typename Weight>
class Graph
{
    struct Edge
    {
        std::string from;
        std::string to;
        Weight      weight;
    };

    struct LargestWeight
    {
        bool operator() (const Edge& e1, const Edge& e2) const
        {
            if (EpsEqual(e1.weight == e2.weight))
                if (e1.from == e2.from)
                    return e1.to < e2.to;
                else
                    return e1.from < e2.from;
            return EpsLess(e2.weight, e1.weight);
        }
    };

    // .. other stuff
};
模板
类图
{
结构边
{
std::来自的字符串;
std::字符串到;
重量;
};
结构最大重量
{
布尔运算符()(常数边和e1、常数边和e2)常数
{
如果(EpsEqual(e1.weight==e2.weight))
if(e1.from==e2.from)
返回e1.to

当权重类型为unsigned或int时,是否会遇到无法预料的后果?还是有更好的方法实现双重比较?

这正是模板的用途


我建议您在只使用
的模板类中实现
EpsLess
()。不,您不能在所有情况下都信任整数到双精度的转换

从整数到双精度的转换不能总是在不损失精度的情况下完成。因此,如果权重是一个可以容纳大值的整数类型,例如大小\u t,则可能会出现问题


所有32位整数都可以毫无问题地进行转换(也称为精度损失)。

@user2079303:我使用ε来区分<(xtemplate<typename Type> Compare { public: template<typename Ignore> inline bool EpsLess(Type x, Type y, Ignore epsilon = Ignore()) { return x < y; } };
template<> Compare<double> {

public:
    inline bool EpsLess(double x, double y, double epsilon = 1.e-10)
    {
        return x < y - epsilon;
    }
};
if (Compare<Weight>::EpsEqual(e1.weight, e2.weight))