简体   繁体   English

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

[英]How to statically check that two ratios are equal?

I have 4 int constants:我有 4 个 int 常量:

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

and I want to statically check that they have the same ratio.我想静态检查它们是否具有相同的比率。 To statically check, I am using BOOST_STATIC_ASSERT , but it doesn't support expressions.要静态检查,我使用的是BOOST_STATIC_ASSERT ,但它不支持表达式。

I tried this:我试过这个:

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

but this produces next compiling errors:但这会产生下一个编译错误:

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

How to fix the above line in order to make the compilation pass?如何修复上述行以使编译通过?

PS I do not have access to c++0x features and std::static_assert, that is why I am using boost's static assert. PS 我无法访问 c++0x 功能和 std::static_assert,这就是我使用 boost 的 static 断言的原因。

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

How to fix the above line in order to make the compilation pass?如何修复上述行以使编译通过?

Without resorting to user763305's elegant rewrite of the equation, you cannot.如果不求助于 user763305 对等式的优雅重写,你就做不到。 The compiler is right: “floating-point literal cannot appear in a constant-expression”.编译器是对的:“浮点文字不能出现在常量表达式中”。 Furthermore, you also cannot call functions ( std::abs ) in constant expressions.此外,您也不能在常量表达式中调用函数( std::abs )。

C++0x will solve this using constexpr . C++0x 将使用constexpr解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM