N-dimensional arrays of arbitrary type and size in C++:
This answer is inspired by the answer of Pavel Radzivilovsky, thanks for that. I had a bit of a hard time realizing the implementation, as it was my first stab at recursive templates. I'd like to share what I have done such that others can understand more quickly than I did.
I have written a c++ template class to create a n-dimensional array of arbitrary type and size. It needs to be instantiated with the array type and the number of dimensions. The size can be changed dynamically. I've given below a bare (stripped) working version of how to create a multidimensional array of which the elements can be accessed through successive application of the operator[] (e.g. array[x][y][z]). This version can only handle arrays of dimension n>1. The main function shows how to create a 4-dimensional array of integers as an example.
EDIT: keep in mind that the example below is minimal for readability, in that it does not deallocate the array, nor does it do bounds checking on access. Adding this is trivial, and left to the programmer.
#include <stdio.h>
#include <stdlib.h>
template <typename T, int N>
struct array {
array<T,N>() : data(NULL), offset((int*) malloc(sizeof(int)*N)){}
array<T,N>(T *data, int *offset) : data(data), offset(offset){}
array<T,N-1> operator[](int i){return array<T,N-1>(&data[i*offset[N]], offset);}
bool resize(int *size){
offset[N-1] = 1;
int total_size = size[N-1];
for(int i = N-2; i >= 0; i--){
total_size *= size[i];
offset[i] = offset[i+1]*size[i+1];
}
return (data = (T*) realloc (data, total_size*sizeof(T)));
}
T *data;
int *offset;
};
template <typename T>
struct array<T,1>{
array<T,1>(T *data, int *offset) : data(data){}
T& operator[](int i){return data[i];}
T *data;
};
int main () {
array<int, 4> a;
// create array with dimensions [1][3][3][7]
int size[4] = { 1, 3, 3, 7 };
a.resize(size);
a[0][1][2][3] = 123;
return 0;
}
Enjoy.