【问题标题】:static_cast / float / bitset / const weirdnessstatic_cast / float / bitset / const 怪异
【发布时间】:2012-08-19 23:46:41
【问题描述】:

就在几个小时前,出现了以下问题:Variable cannot appear in a constant-expression

幸运的是,提供的答案确实解决了他的问题,但我无法重现该解决方案。

我试图进一步简化代码,但现在我遇到了以下问题:

#include <bitset>

int main ()
{
   const size_t length_1 = static_cast<const size_t>(1.0f);
   std::bitset<length_1> bits_1;
   const size_t length_2 = static_cast<const size_t>(1.0f / 1.0f);
   std::bitset<length_2> bits_2;
}

如果使用-pedantic 编译,编译器会接受第一个示例,但带有除法(但显然相同的数字)的示例会被拒绝,并显示消息“length_2 不能出现在常量表达式中”。

如果没有-pedantic-pedantic -std=c++0x,它会在没有任何进一步警告的情况下被接受。

这是g++ -v 的完整输出(我为德语道歉,但我相信无论如何你得到了正确的信息):

Es werden eingebaute Spezifikationen verwendet.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-linux-gnu/4.6/lto-wrapper
Ziel: i686-linux-gnu
Konfiguriert mit: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.3-1ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu
Thread-Modell: posix
gcc-Version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 

这种行为的原因是什么?我猜这是1.0fbeeing 被识别为一些特殊的常数,因此改变了 static_cast 的行为?

【问题讨论】:

  • 请随意提出一个比“怪异”更好的标题,我现在有点困
  • 我想我在这里找到了解决这个混乱的可能答案:velocityreviews.com/forums/…“动机不是要求交叉编译器来实现目标机器的浮点运算。”但我会让对此了解更多的人提供答案。它在 VS2010 中工作的事实是有道理的,因为它不支持交叉编译。
  • 另外,-pedantic -std=c++0x 的神奇组合对我不起作用,我不知道为什么。鉴于上面的引用,我希望即使没有-pedantic,它也会拒绝我的代码......无论如何,我将在没有-pedantic 的情况下编译,就是这样。

标签: gcc g++ bitset static-cast gcc-pedantic


【解决方案1】:

答案在 §5.19 中。

C++03 只允许 算术常量表达式 满足 整数常量表达式 的要求:“浮动文字 (2.13.3) 只有在满足强制转换为整数或枚举类型。”

因此,虽然将1.0f/1.0f 视为1 似乎是合理的,但它仍然超出了标准。避免“目标机器的浮点运算”对我来说听起来像是一个很好的解释。 GCC 4.7 需要 libgmp、libmpfr 和 libmpc 才能完成这项工作。

C++11 没有这样的限制。但是准确性仍然是实现定义的。 仅“鼓励”实现为编译时和运行时评估提供一致的结果。

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 2021-12-31
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多