How can I avoid the division by zero warning in this pattern?

I have a class for fixed point arithmetic, of which this is the main part:

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."); }; 

In GCC 4.4.5, the following line of code:

 fixed<int, 8> f = fixed<int, 2>(1); 

Generates an error:

 fixed.hpp: In constructor 'fixed<I, S>::fixed(const fixed<J, T>&) [with J = int, JT = 2, I = int, IS = 8]': fixed.hpp:81: error: division by zero 

As long as the code has division by constant zero - one of T / S or S / T should be equal to zero for unequal scales - if S% T == 0 (and S is not equal to 0), then S / T is not equal to zero. It seems that GCC is doing enough optimization to realize that one of my branches is guaranteed to be divisible by zero, but not optimizing enough to find out that the branch is guaranteed to not work.

I can throw #pragma GCC diagnostic ignored "-Wdiv-by-zero" into the file, but this can mask the real warnings.

How to deal with this situation? (Or is my analysis completely wrong and do I have a real division by zero?)

+8
c ++ templates g ++ integer-division
source share
2 answers

something like?

 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(...); 

or using mpl::bool_ , you can "specialize" functions through parameters.

+7
source share

You can use a support pattern to separate and specialize it for hard coding an arbitrary value (if it will not be used) when the divisor is 0.

0
source share

All Articles