C++常量表达式和数组边界

kvs*_*kvs 2 c++

有人可以在下面的代码中解释(可能是我认为的)错误差异吗?基本上为什么"// OK"没问题和"//错误"错误?

(编译器是i686-apple-darwin9-g ++ - 4.0.1(GCC)4.0.1(Apple Inc. build 5490))

#include <cmath>
#include <iosfwd>

template <typename T>
class TT{
   char _c[sizeof(T) + static_cast<size_t>(::ceil(sizeof(T) * 0.001)) + 1];    // error: array bound is not an integer constant
   //char _c[sizeof(T) + static_cast<size_t>(sizeof(T) * 0.001) + 1];  // OK
   T _t;
};

class IS{
   unsigned char* _u;
   double _d;
};

char s[static_cast<size_t>(::ceil(sizeof(TT<IS>) * 10.0))]; // error: array bound is not an integer constant

int main(int argc, char** argv){
  char a[static_cast<size_t>(10.0)];  // OK
  char b[static_cast<size_t>(::ceil(sizeof(double) * 10.0))]; // OK

  TT<int> it;
  char c[static_cast<size_t>(::ceil(sizeof(TT<int>) * 10.0))];    // OK

  TT<IS> is;
  char d[static_cast<size_t>(::ceil(sizeof(TT<IS>) * 10.0))]; // OK

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

作为旁注,我知道C++ 0x:广义常量表达式.

sha*_*oth 5

问题在于声明数组的位置.

您可以在文件级别声明一个非常大小的数组,因为编译器需要在编译时知道分配多少,在您的情况下,这将需要函数调用.

当您在功能级别执行相同操作时,编译器支持的C++扩展支持(标准不允许) - 编译器发出的代码将调用函数,计算值并在运行时在堆栈上分配数组.