C ++ Const expression and array bounds
Can someone please explain (what my perception might be) the inconsistency in the errors in the following code? Basically, why is "// OK" OK and "// errors"?
(Compiler - 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;
}
As a side note, I know about C ++ 0x: Generic Constant Expression.
source to share
The problem is where the arrays are declared.
You can declare an array with a non-constant size at the file level, since the compiler needs to know at compile time how much to allocate, and in your case, this would require a function call.
When you do the same at the function level, a C ++ extension supported by your compiler (this is not permitted by the standard) - the compiler emits code that is called by the function, computes the value, and pushes the array onto the stack at runtime.
source to share