Domanda

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.

edit: I also must not use new.

Thanks

È stato utile?

Soluzione

In some cases like this, I'll add a function get_array_size<e>(). Since you say you don't have constexpr, there's still decent possibilities:

//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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top