问题描述
我有一个定点算术的类,其中这是显着的部分:
I have a class for fixed-point arithmetic, of which this is the salient portion:
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.");
};
在GCC 4.4.5上,以下代码行:
On GCC 4.4.5, the following line of code:
fixed<int, 8> f = fixed<int, 2>(1);
产生错误:
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
是代码中的常数零 - 对于不等量程,T / S或S / T中的一个必须为零 - 如果S%T == 0(且S不为0),则S / T不为零。 GCC似乎正在做足够的优化,以确定我的一个分支保证除以零,但没有足够的优化,以确定该分支保证不运行。
While there is a division by constant zero in the code - one of T/S or S/T must be zero for unequal scales - if S%T == 0 (and S is not 0), then S/T is not zero. GCC seems to be doing just enough optimization to figure out that one of my branches is guaranteed to divide by zero, but not enough optimization to figure out that branch guaranteed to not run.
我可以在文件中抛出 #pragma GCC诊断忽略的-Wdiv-by-zero
,但存在掩盖真实警告的风险。
I can throw #pragma GCC diagnostic ignored "-Wdiv-by-zero"
in the file, but that risks masking real warnings.
处理这种情况的适当方法是什么? (或者我的分析是完全错误的,我有一个真正的运行时除以零?)
What's the appropriate way to handle this situation? (Or is my analysis totally wrong and I do have a real runtime division by zero?)
推荐答案
像? >
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(...);
或使用 mpl :: bool _
通过参数专业化功能。
or using mpl::bool_
you could "specialize" functions through parameters.
这篇关于如何避免在此模板代码中的除以零的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!