如何在此模板代码中避免关于除零的警告?

8 c++ templates g++ integer-division

我有一个定点算术类,其中这是一个显着的部分:

template <typename I, I S>
struct fixed
{
    I value;

    fixed(I i) : value(i * S) {}

    template <typename J, J T> fixed(const fixed<J, T> &fx)
    {
        if (S % T == 0)
            value = fx.value * (S / T);
        else if (T % S == 0)
            value = fx.value / (T / S);
        else
            value = S * fx.value / T;
    }

    static_assert(S >= 1, "Fixed-point scales must be at least 1.");
};
Run Code Online (Sandbox Code Playgroud)

在GCC 4.4.5上,以下代码行:

fixed<int, 8> f = fixed<int, 2>(1);
Run Code Online (Sandbox Code Playgroud)

生成错误:

fixed.hpp: In constructor ‘fixed<I, S>::fixed(const fixed<J, T>&) [with J = int, J T =     2, I = int, I S = 8]’:
fixed.hpp:81: error: division by zero
Run Code Online (Sandbox Code Playgroud)

虽然在代码中有一个除以零的部分 - 对于不等的比例,T/S或S/T中的一个必须为零 - 如果S%T == 0(并且S不为0),那么S/T不为零.GCC似乎正在做足够的优化,以确定我的一个分支保证除以零,但没有足够的优化来确定该分支保证不运行.

我可以扔进#pragma GCC diagnostic ignored "-Wdiv-by-zero"文件,但这有可能掩盖真正的警告.

处理这种情况的适当方法是什么?(或者我的分析是完全错误的,我确实有一个真正的运行时划分为零?)

Any*_*orn 7

就像是?

template<int,int>
struct helper {
    static int apply(...) { return S * fx.value / T; }
};

template<int n>
struct helper<0,n> { // need 0,0 as well to avoid ambiguity
    static int apply(...) { return fx.value * (S / T); }
};

template<int m>
struct helper<m,0> {
    static int apply(...) { return fx.value / (T / S); }
};

helper<(S % T == 0), (T % S == 0)>::apply(...);
Run Code Online (Sandbox Code Playgroud)

或者使用mpl::bool_你可以通过参数"专门化"功能.