繁体   English   中英

如何消除模板代码中的“除以0”错误

[英]How to eliminate “divide by 0” error in template code

我使用一对整数模板参数来指定比率,因为我不能使用double作为模板参数。 转换为双精度可以防止零三进制。 这在早期版本的编译器中有效,但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 ,但我相信你可以constexpr进行排序......)

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;
    }
};

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM