简体   繁体   English

如何在模板中初始化成员数组

[英]How to initialize a member array in a template

I would like to have an array which has a length that depends on the parameter of my template, but I keep getting the "expected constant expression" error. 我想拥有一个长度取决于我的模板参数的数组,但是我不断收到“期望的常量表达式”错误。

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;

The compiler I must use does not support constexpr , or any other C++ 11 features, and I also cannot pass the array size as a template parameter. 我必须使用的编译器不支持constexpr或任何其他C ++ 11功能,并且我也无法将数组大小作为模板参数传递。

edit: I also must not use new . 编辑:我也一定不能使用new

Thanks 谢谢

In some cases like this, I'll add a function get_array_size<e>() . 在这种情况下,我将添加一个函数get_array_size<e>() Since you say you don't have constexpr, there's still decent possibilities: 由于您说自己没有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 http://coliru.stacked-crooked.com/a/f03a5fa94a038892

Are we reinventing the wheel here ? 我们在这里重新发明轮子吗? Enums are compile time constants . 枚举是编译时间常数 Just do this : 只要这样做:

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

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

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM