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

标签 c++ boost static-assert

我有 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 的静态断言的原因。

最佳答案

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

关于c++ - 如何静态检查两个比率是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6279410/

相关文章:

c++ - boost 线程 - 使用局部变量作为参数

c++ - 使用 OpenCV 在图像上悬停时打印鼠标指针的像素坐标

c++ - Qt for wasm : error: use of undeclared identifier 'QThreadPool'

c++ - 虚拟调试类卡在 std::endl 重载上

c++ - 为什么我的简单 cpp-netlib 程序需要这么长时间才能编译?

c++ - Boost 文件系统教程无法编译

c++ - static_assert 中的 std::pow 触发错误 C2057?

c++11 - 如何使用 C++11 static_assert 进行类型约束?

c++ - 由于类型不完整,在 static_assert 中使用 std::is_base_of 失败

c++ - SEGFAULT 使用 MySQL/C++ 连接器获取结果