jeudi 28 mai 2015

How do I use a static array element as an index to a static array of objects that are of different template instantiations

How do I use a static array element as an index to a static array of objects that are of different template instantiations?

I'm stuck getting the obvious compiler error: invalid template argument for 'N', expected compile-time constant expression.

I don't know if there's a non-c++11 answer. Hopefully there's something modern that I can use in vs2013... :)

I'm trying to store data statically like so:

static const char* size1Array[1] =
{
    "hello"
};

static const char* size2Array[2] =
{
    "foo",
    "bar"
};

static const size_t ARRAYSIZES[2] =
{
    1,
    2
};

// Empty parent
struct DataParent {};

template <size_t N>
struct DataChild
{
    DataChild(const char*(*arrIn)[N])
        : arr(arrIn) {}

    const char*(*arr)[N];
};

// The arrays are of different sizes, hence the DataParent to keep them in a static array
static DataParent DataTable[ 2 ] =
{
    DataChild< 1 >(&size1Array),
    DataChild< 2 >(&size2Array)            
};

int main()
{
    int index = 1;
    // The tricky cast that won't compile (ARRAYSIZES[index] 
    std::cout << ((DataChild< ARRAYSIZES[index] >*)&DataTable[index])->arr[0] << std::endl;
}

I want access to the objects in the static array but I can't do it with a non-compile constant. I'm running VS2013 Update 4.

Aucun commentaire:

Enregistrer un commentaire