I’m searching for a way to define an array as a class-member with an undefined size (which will be defined on initialization).
class MyArrayOfInts {
private:
int[] array; // should declare the array with an (yet) undefined length
public:
MyArrayOfInts(int);
int Get(int);
void Set(int, int);
};
MyArrayOfInts::MyArrayOfInts(int length) {
this->array = int[length]; // defines the array here
}
int MyArrayOfInts::Get(int index) {
return this->array[index];
}
void MyArrayOfInts:Set(int index, int value) {
this->array[index] = value;
}
How can I achieve this behaviour ?
Proof Of Concept
Ok, inspired by UncleBens challenge here, I came up with a Proof-Of-Concept (see below) that let’s you actually do:
It revolves around a template trick in
factory<>::instantiatethat actually uses a compile-time meta-binary-search to match the specified (runtime) dimension to a range of explicitstatic_arrayclass template instantiations.I feel the need to repeat that this is not good design, I provide the code sample only to show what the limits are of what can be done – with reasonable effor, to achieve the actual goal of the question. You can see the drawbacks:
DEMO_MAX = 256,g++ -Oswill actually emit 258 instantiations offactory<>;g++ -O4will keep 74 of those, inlining the rest[2]DEMO_MAX = MAX_RANDcompilation takes about 2m9s to… run out of memory on a 64-bit 8GB machine; atMAX_RAND>>16it takes over 25 minutes to possibly compile (?) while nearly running out of memory. It would really require some amounts of ugly manual optimization to remove these limits – I haven’t gone so insane as to actually do that work, if you’ll excuse me.[2] established that with
objdump -Ct test | grep instantiate | cut -c62- | sort -k1.10nShow me the CODE already!