static_cast / float / bitset / const怪异

时间:2012-08-19 23:46:42

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

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

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

我试图进一步简化代码,现在我仍然坚持以下内容:

#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不能出现在常量表达式中”。< / p>

如果没有-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.0f beeing被认为是一些特殊的常量,因此改变了static_cast的行为?

1 个答案:

答案 0 :(得分:2)

答案在§5.19。

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

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

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