如何静态地检查两个比率是否相等?

5

我有4个整数常量:

const int a1 = 1024;
const int a2 = 768;
const int b1 = 640;
const int b2 = 480;

我希望能够静态检查它们是否具有相同的比例。为了进行静态检查,我使用了BOOST_STATIC_ASSERT,但它不支持表达式。

我尝试过这样:

BOOST_STATIC_ASSERT( 1e-5 > std::abs( (double)a1 / (double)a2 - (double)b1 / (double)b2 ) );

但是这会产生下一次编译错误:
error: floating-point literal cannot appear in a constant-expression
error: 'std::abs' cannot appear in a constant-expression
error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression
error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression
error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression
error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression
error: a function call cannot appear in a constant-expression
error: template argument 1 is invalid

如何修改上述行以使编译通过?
PS:我无法使用c++0x功能和std::static_assert,因此我正在使用boost的静态断言。
2个回答

9
BOOST_STATIC_ASSERT(a1 * b2 == a2 * b1);

+1:数学上是更好的选择。但问题仍然是,如何解决他的编译错误。 - Martijn Courteaux
3
@Martijn,我认为这是唯一的方法。请查看Konrad的回复。 - BЈовић
请注意,如果发生溢出,则可能无法正常工作。 - TLW

8
如何修复上述代码行以使编译通过?
除非使用用户763305的优雅重写方程,否则无法解决。编译器是正确的:“浮点数文字不能出现在常量表达式中”。此外,在常量表达式中也不能调用函数(std::abs)。C++0x将使用constexpr来解决这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接