所以我刚刚通过编译器错误了解到数组的类内初始化是无效的(为什么?)。现在我想在模板类中初始化一些数组,不幸的是内容依赖于模板参数。精简的测试用例如下所示:
template<typename T>
struct A {
T x;
static const int len = sizeof(T); // this is of course fine
static const int table[4] = { 0, len, 2*len, 3*len }; //this not
}
知道如何拉出常数数组吗?
编辑:添加'int'。
答案 0 :(得分:5)
正如你没有模板那样做;把初始化放在类的声明之外:
template<class T>
const int A<T>::table[4] = { 0, len, 2*len, 3*len };
答案 1 :(得分:2)
class Y
{
const int c3 = 7; // error: not static
static int c4 = 7; // error: not const static const
float c5 = 7; // error not integral
};
为什么存在这些不方便的限制?类通常在头文件中声明,并且头文件通常包含在许多翻译单元中。但是,为避免复杂的链接器规则,C ++要求每个对象都有唯一的定义。如果C ++允许将需要作为对象存储在内存中的实体的类内定义,则该规则将被破坏。
答案 2 :(得分:0)
template <typename T, int index>
struct Table {
static const len = sizeof(T);
static const value = len*index;
};