首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何静态检查两个比率是否相等?

如何静态检查两个比率是否相等?
EN

Stack Overflow用户
提问于 2011-06-08 21:23:58
回答 2查看 469关注 0票数 5

我有4个int常量:

代码语言:javascript
复制
const int a1 = 1024;
const int a2 = 768;
const int b1 = 640;
const int b2 = 480;

我想静态地检查它们是否有相同的比率。为了进行静态检查,我使用了BOOST_STATIC_ASSERT,但它不支持表达式。

我试过这个:

代码语言:javascript
复制
BOOST_STATIC_ASSERT( 1e-5 > std::abs( (double)a1 / (double)a2 - (double)b1 / (double)b2 ) );

但这会产生下一个编译错误:

代码语言:javascript
复制
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的静态断言。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-08 21:26:37

代码语言:javascript
复制
BOOST_STATIC_ASSERT(a1 * b2 == a2 * b1);
票数 9
EN

Stack Overflow用户

发布于 2011-06-08 21:25:54

如何修复上面的代码行以使编译通过?

如果不求助于user763305对等式的优雅重写,你就不能。编译器是正确的:“浮点文字不能出现在常量表达式中”。此外,您也不能在常量表达式中调用函数(std::abs)。

C++0x将使用constexpr解决此问题。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6279410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档