下面的代码演示了我无法解释的gcc 4.6.2的行为.第一个函数声明一个类型为vec_t的静态数组,其中vec_t是unsigned char的typedef'd别名.除了vect_t的类型是模板参数之外,第二个函数是相同的.第二个函数无法使用诊断编译"错误:'bitVec'的存储大小不是常量".
#include <limits>
void bitvec_func()
{
const std::size_t nbits = 1e7;
typedef unsigned char vec_t;
const std::size_t WLEN = std::numeric_limits<vec_t>::digits;
const std::size_t VSIZ = nbits/WLEN+1;
static vec_t bitVec[nbits/VSIZ]; // Compiles fine
}
template <typename T>
void bitvec_func()
{
const std::size_t nbits = 1e7;
typedef T vec_t;
const std::size_t WLEN = std::numeric_limits<vec_t>::digits;
const std::size_t VSIZ = nbits/WLEN+1;
static vec_t bitVec[nbits/VSIZ]; // "error: storage size of ‘bitVec’ isn’t constant"
}
void flarf()
{
bitvec_func();
bitvec_func<unsigned char>();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,使用参数<unsigned char>实例化模板应该使编译器生成与第一个函数相同的代码.任何人都可以提供任何洞察力,为什么这似乎不是这样的?
[附录:第二个函数 …
必须将非整数常量(显式或隐式)转换为整数类型,使其在常量表达式中是合法的.因此,以下代码是合法的:
Run Code Online (Sandbox Code Playgroud)const double Size = 11.0; char chArray[(int)Size];
至少在VC++ 10.0上,第二行产生:"错误C2057:预期的常量表达式".那么它在某些其他编译器上是合法的还是msdn页面完全错了?