如何静态检查两个比率是否相等
How to statically check that two ratios are equal?
我有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);
如何修复上面的行以使编译通过?
如果不求助于user763305对等式的优雅重写,你就无法做到这一点。编译器是对的:"浮点文字不能出现在常量表达式中"。此外,您也不能在常量表达式中调用函数(std::abs
)。
C++0x将使用CCD_ 3来解决此问题。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 根据单个持续时间和比率计算两个持续时间的正确方法
- 尝试获得两个数字的"adjusted"比率
- 如何静态检查两个比率是否相等