Suppose I have the C++ code below
template <int Id>
struct Foo {
static inline int x {};
};
int main() {
using T0 = Foo<0>;
using T1 = Foo<1>;
...
using T999 = Foo<999>;
// Do some stuff with the various x's at runtime
int result = T0::x + T1::x + ... + T999::x;
}
Now inspect the sum in the final line. Is there any guarantee that the various static x's will be stored contiguously in memory and that this sum will be efficient cache wise? Or in general should one assume that the static variables are just stored in some random order in random places in such a way that would not be cache efficient.
In the case of the former is it because the using statements appear in order? Does template instantiation occur because of the presence of a using statement or does the template actually have to be used (in which case maybe they are stored in usage order)?
In the case of the latter would using a tuple of size 1000 and each Foo::x using the n-th index in that tuple as its variable solve that problem?
Although it might be the case for it to be allocated contigously, it's not actually guaranteed. It's better to create an array and make constant indexes to refer to particular fragments, e.g.
const variable7_ind = 7and then useT[variable7_ind]instead ofT7.