Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to statically check that two ratios are equal?

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.

like image 958
BЈовић Avatar asked Jun 08 '11 13:06

BЈовић


2 Answers

BOOST_STATIC_ASSERT(a1 * b2 == a2 * b1);
like image 179
Johan Råde Avatar answered Sep 23 '22 23:09

Johan Råde


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.

like image 39
Konrad Rudolph Avatar answered Sep 22 '22 23:09

Konrad Rudolph