lundi 18 septembre 2017

Template argument - address of array element

I have the following definition:

template<int* B> class T { ... }

Inside T, however, I access B[-n], where n > 0. So, this is what I want to do:

#define MAXN 1000
int N[2*MAXN];
T<N + MAXN> t;

This is not allowed, according to the compiler. cppreference even has an example of this particular case saying it does not work, and I have already searched everywhere else for a solution (none to be found yet). I do understand how templates work, and I do know that (and why) the value of each template argument must be known during compilation time. I understand the compiler does not know the address of N in compilation time, only determines that later during linking. I'm, however, finding it hard to accept there isn't a solution here.

So, I'm wondering if anyone knows a way around this that does not require modifying T. My only idea so far was:

int N_neg[MAXN], N[MAXN]; // defined in the global scope!
T<N> t;

But does it work with ALL compilers? Is it guaranteed, for all compilers, that &N == &N_neg[MAXN]? If so, I'm done, this is all I need. If not, any ideas?

NOTE: This is meant for programming contests only, so don't worry about maintainability. I'm more concerned about keeping T easy to understand.

Aucun commentaire:

Enregistrer un commentaire