【问题标题】:How to statically check that two ratios are equal?如何静态检查两个比率是否相等?
【发布时间】:2011-06-08 13:23:57
【问题描述】:

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

【问题讨论】:

    标签: c++ boost static-assert


    【解决方案1】:
    BOOST_STATIC_ASSERT(a1 * b2 == a2 * b1);
    

    【讨论】:

    • +1:这在数学上更好。但问题仍然是,如何解决他的编译错误。
    • @Martijn 我认为上面是唯一的方法。查看康拉德的回应
    • 请注意,如果出现溢出,这可能不起作用。
    【解决方案2】:

    如何修正上述行以使编译通过?

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

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

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2015-10-30
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多