I have 4 int constants :
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.
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.
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. The compiler is right: “floating-point literal cannot appear in a constant-expression”. Furthermore, you also cannot call functions (std::abs
) in constant expressions.
C++0x will solve this using constexpr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With