我有4個INT常數:如何靜態檢查兩個比率是否相等?
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的靜態斷言。
+1:這在數學上更好。但問題仍然是,如何解決他的編譯錯誤。 – 2011-06-08 13:38:48
@Martijn我認爲以上是唯一的方法。見康拉德的迴應 – 2011-06-08 13:39:33