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

BЈо*_*вић 5 c++ boost static-assert

我有4个int常量:

const int a1 = 1024;
const int a2 = 768;
const int b1 = 640;
const int b2 = 480;
Run Code Online (Sandbox Code Playgroud)

我想静态检查它们是否具有相同的比例.要静态检查,我正在使用BOOST_STATIC_ASSERT,但它不支持表达式.

我试过这个:

BOOST_STATIC_ASSERT( 1e-5 > std::abs( (double)a1 / (double)a2 - (double)b1 / (double)b2 ) );
Run Code Online (Sandbox Code Playgroud)

但这会产生下一个编译错误:

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
Run Code Online (Sandbox Code Playgroud)

如何修复上面的行以使编译通过?

PS我无法访问c ++ 0x功能和std :: static_assert,这就是我使用boost的静态断言的原因.

Joh*_*åde 9

BOOST_STATIC_ASSERT(a1 * b2 == a2 * b1);
Run Code Online (Sandbox Code Playgroud)

  • @Martijn我认为上面是唯一的方法.请参阅Konrad的回复 (3认同)

Kon*_*lph 8

如何修复上面的行以使编译通过?

如果不依靠user763305的优雅重写方程,你就不能.编译器是对的:"浮点文字不能出现在常量表达式中".此外,您也无法std::abs在常量表达式中调用函数().

C++ 0x将解决这个问题constexpr.