如何消除模板代码中的"divide by 0"错误



我正在使用一对整数模板参数来指定比率,因为我不能使用双精度作为模板参数。转换为双精度值时,防止使用三元除以零。这在早期版本的编译器中有效,但Visual Studio 2013给出了一个错误:

error C2124: divide or mod by zero

下面是代码的简化版本:

template<int B1, int B2>
class MyClass
{
    const double B = (B2 == 0) ? 0.0 : (double) B1 / (double) B2;
    // ...
};
MyClass<0, 0> myobj;

我真的希望B从在零时使用它的表达式中优化出来,所以我需要单行定义。我知道我可以使用模板参数<0, 1>来解决它,但我想知道是否有办法让编译器相信我的表达式是安全的?

我被告知的是:

 const double B = (B2 == 0 ? 0.0 : (double) B1) /
                  (B2 == 0 ? 1.0 : (double) B2);

这避免了对短路评估的依赖,从而防止除以0;在除法之前进行条件选择。


最初的想法/也许是这样的...? (我认为B应该是static constconstexpr,但我相信你可以排序......

template<int B1, int B2>
struct MyClass
{
    const double B = (double) B1 / (double) B2;
};
template <int B1>
struct MyClass<B1, 0>
{
    const double B = 0.0;
};

如果您想要MyClass还有很多其他内容,并且不想复制或放入基础等,则可以使用上面的专业化方法将B计算移动到支持模板中。

Visual Studio无法在编译时以三元操作类型转换B1,B2,但显式转换将起作用。

template<int B1, int B2>
class MyClass
{
    double d1 = (double)B1;
    double d2 = (double)B2;
    const double B = (B2 == 0) ? 0.0 : d1/d2;
    // ...
};
MyClass<0, 0> myobj;

对于好奇的人 - 这是我最终得到的代码。在现实世界的背景下看到它可能会有所帮助。

template<int B1, int B2, int C1, int C2>
class BicubicFilter
{
    // Based on the formula published by Don Mitchell and Arun Netravali at
    // http://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf
public:
    BicubicFilter() : m_dMultiplier(1.0) {}
    double m_dMultiplier;
    double k(double x) const
    {
        const double B = (double) B1 / ((B2 == 0) ? 1.0 : (double) B2);
        const double C = (double) C1 / ((C2 == 0) ? 1.0 : (double) C2);
        x = fabs(x) * m_dMultiplier;
        if (x < 1.0)
            return ((2.0 - 1.5*B - C) * x*x*x) + ((-3.0 + 2.0*B + C) * x*x) + (1.0 - (2.0/6.0)*B);
        if (x < 2.0)
            return (((-1.0/6.0)*B - C) * x*x*x) + ((B + 5.0*C) * x*x) + ((-2.0*B - 8.0*C) * x) + ((8.0/6.0)*B + 4.0*C);
        return 0.0;
    }
};

对于图像大小调整操作,每个像素至少执行 4 次 k 函数,因此效率至关重要。我希望在编译时知道所有常量,以便编译器可以尽可能简化表达式。

基于接受的答案,我希望创建一个Ratio模板类,该类将简单地产生两个int的比率作为constexpr double,并将其专门用于0, 0参数。Visual Studio 2013尚未实现constexpr因此我不相信编译器会将其视为编译时常量。幸运的是,原始三元表达式的变体消除了错误。

最新更新