2014-05-14 44 views
0

我想有一个数组的长度取决于我的模板的参数,但我不断收到“预期的常量表达式”错误。如何初始化模板中的成员数组

enum MyEnum 
{ 
    FIRST, 
    OTHER 
}; 

template<MyEnum e> 
struct MyTemplate 
{ 
    static const int arrSize; 
    int myArr[arrSize];   // error C2057: expected constant expression 
    // int myArr[e == FIRST ? 4 : 10]; // works, but isn't very readable... 
}; 

template<> 
const int MyTemplate<FIRST>::arrSize = 4; 

template<> 
const int MyTemplate<OTHER>::arrSize = 10; 

我必须使用编译器不支持constexpr,或任何其他C++ 11个特征,我也不能传递数组大小作为模板参数。我也不能使用new

感谢

+0

你不能做到这一点,编译器必须知道'arrSize'当你宣布'INT myArr,该[arrSize]' – 101010

+1

IMO,'é== FIRST? 4:10'比引入模板专业化更具有可读性......使用'template'关键字的次数越多,代码的可读性就越差 – Brian

+0

@Brian这是一个例子,但我有10多种可能性码。 – phil

回答

5

在某些情况下是这样,我将添加一个功能get_array_size<e>()。既然你说你没有constexpr,还是有体面的可能性:

//I call this a pseudo-template-function, but there's probably better names 
template<MyEnum> struct GetArraySize; //compiler error for default 
template<> struct GetArraySize<FIRST> {static const int value=4;}; 
template<> struct GetArraySize<OTHER> {static const int value=10;}; 

template<MyEnum e> 
struct MyTemplate 
{ 
    static const int arrSize = GetArraySize<e>::value; 
    int myArr[arrSize]; 
}; 

http://coliru.stacked-crooked.com/a/f03a5fa94a038892

+0

虽然我还没有想出如何获得MyTemplate的这个_inside_。 –

+0

它的工作原理,感谢:-) – phil

1

我们在这里重新发明轮子? 枚举是编译时间常量。只是这样做:

enum MyEnum 
{ 
    FIRST = 4, 
    OTHER = 10 
}; 

template<MyEnum e> 
struct MyTemplate 
{ 
    int myArr[e];  
}; 

demo

+1

我不能,因为枚举有一些其他值在其他地方使用。 – phil

+1

仍然,不是一个不错的答案在页面上有 –

+0

然后采取该值,并添加N其中N是您想要的结果数减去值 –

相关问题