I'm representing coordinates in a multi-dimensional array, and I'd like to stick as closely to native arrays as possible.
nArray.hpp
#include <stdexcept>
// Array that allows for negative integers
template <typename T, int SIZE> struct nArray {
private:
T array[SIZE];
public:
nArray() {
if ((SIZE + 1) % 2 != 0) {
throw std::length_error("Array size must be odd number");
}
}
T& operator[] (int index) {
if (abs(index) > (SIZE-1)/2) {
throw std::out_of_range("Array index is out of bounds");
}
return array[index + SIZE/2];
}
};
So something like nArray<nArray<int, 100>, 100> array;
is a 2-dimensional array in which either bracket can accept any index whose absolute value is less than or equal to 50 without entering undefined-behavior territory (e.g. - array[-40][10]
). As far as I can tell, it works as intended (specifically, things that crashed when I tried to give negative indices on a regular multi-dimensional array do not crash when I use negative indices on nArray), but I wouldn't be surprised if there is a lot of potentially dangerous stuff going on under-the-hood that I'm unaware of.
Does this look ok, or is this an example of how ignorance can destroy computers?
array[-40][10]
and that is all I am asking about; I think a "proper code review" would answer my question, which doesn't require anything outside of that example. Is my overloading of the[]
operator sound, or are there native-array landmines I'm stepping on by doing this? \$\endgroup\$