当我打电话时:a7[0][1][100];
我能够获得第一个索引0
,operator[]
但作为索引,我将无法以递归方式获得其他索引值 1 和 100。我如何能够使用operator[]
以获得递归的以下索引值。在此示例中,对于 3 维数组,operator[]
仅对第一个维度(即 )调用一次0
。
我的示例代码如下:
template <class T, unsigned ... RestD> struct array;
template <class T, unsigned PrimaryD>
struct array <T, PrimaryD> {
typedef T type[PrimaryD];
type data;
T& operator[] (unsigned i) {
return data[i];
}
};
template <class T, unsigned PrimaryD, unsigned ... RestD>
struct array <T, PrimaryD, RestD...> {
typedef typename array<T, RestD...>::type OneDimensionDownArrayT;
typedef OneDimensionDownArrayT type[PrimaryD];
type data;
OneDimensionDownArrayT& operator[] (int i) {
OneDimensionDownArrayT& a = data[i];
return a;
}
};
int main () {
array<int, 1, 2, 3> a7 {{{{1, 2, 3},{4, 5, 6}}}};
a7[0][1][2] = 100; //=>won't recursively go through operator[]
//I want to recursively obtain 0, 1 and 2 as index values
a7[0][1][100] = 100; //also works correctly.
std::cout << a7[0][1][100] << std::endl;
return 0;
}