C
Christof Warlich
Hi,
the subject says it all: I need to instantiate an array of objects
where each object "knows" its arrary index. So far, this is easy
as long as index is not a compile-time constant:
class Elements {
public:
Elements():
index(maxIndex) {
maxIndex++;
}
const unsigned int index;
private:
static unsigned int maxIndex;
};
unsigned int Elements::maxIndex = 0;
Elements array[5];
#include <stdio.h>
template<unsigned int x> struct Test {
};
int main(void) {
printf("%d\n", array[4].index);
printf("%d\n", array[2].index);
// No way to create an instance
// of Test<> with index.
}
The point is that I need to use index inside Element as a template
parameter constant, i.e index must be known for each Element instance
at compile time already.
Soemthing like this does work, but does not help as access to the
instances of Element cannot be done in a unique fashion by just
providing index:
template<unsigned int i> struct Array {
class Element {
public:
static const unsigned int index = i;
};
static Array<i - 1> array;
};
template<> struct Array<0> {
class Element {
public:
static const unsigned int index = 0;
};
};
#include <stdio.h>
template<unsigned int x> struct Test {
};
int main(void) {
printf("%d\n", Array<4>::Element::index);
printf("%d\n", Array<4>::Array<3>::Array<2>::Element::index);
Test<Array<4>::Array<3>::Element::index> test;
}
Any ideas how this problem could be solved?
Thanks for any help,
Christof
the subject says it all: I need to instantiate an array of objects
where each object "knows" its arrary index. So far, this is easy
as long as index is not a compile-time constant:
class Elements {
public:
Elements():
index(maxIndex) {
maxIndex++;
}
const unsigned int index;
private:
static unsigned int maxIndex;
};
unsigned int Elements::maxIndex = 0;
Elements array[5];
#include <stdio.h>
template<unsigned int x> struct Test {
};
int main(void) {
printf("%d\n", array[4].index);
printf("%d\n", array[2].index);
// No way to create an instance
// of Test<> with index.
}
The point is that I need to use index inside Element as a template
parameter constant, i.e index must be known for each Element instance
at compile time already.
Soemthing like this does work, but does not help as access to the
instances of Element cannot be done in a unique fashion by just
providing index:
template<unsigned int i> struct Array {
class Element {
public:
static const unsigned int index = i;
};
static Array<i - 1> array;
};
template<> struct Array<0> {
class Element {
public:
static const unsigned int index = 0;
};
};
#include <stdio.h>
template<unsigned int x> struct Test {
};
int main(void) {
printf("%d\n", Array<4>::Element::index);
printf("%d\n", Array<4>::Array<3>::Array<2>::Element::index);
Test<Array<4>::Array<3>::Element::index> test;
}
Any ideas how this problem could be solved?
Thanks for any help,
Christof