正如其他人所说,当您将数组传递给函数时,数组的大小会丢失(除非您通过引用传递)。所以你可以做这样的事情:
/* this function does the work */
template <typename T>
void bar(T* arr, size_t n_dims, size_t* sizes)
{
std::cout << n_dims << " dimension(s)\n";
for (size_t i = 0; i < n_dims; ++i) // for each dimension
for (size_t j = 0; j < sizes[i]; ++j) ; // for each element
}
/* These are helper overloads to call bar with correct arguments. */
/* You'll need to provide one for each number of dimension you want to support */
template<typename T, size_t N>
void foo(T (&arr)[N])
{
size_t sizes[] = {N};
bar(arr, 1, sizes);
}
template<typename T, size_t N, size_t M>
void foo(T (&arr)[N][M])
{
size_t sizes[] = {N, M};
bar(arr, 2, sizes);
}
template<typename T, size_t N, size_t M, size_t O>
void foo(T (&arr)[N][M][O])
{
size_t sizes[] = {N, M, O};
bar(arr, 3, sizes);
}
int main()
{
int arr1[42];
int arr2[2][2];
int arr3[2][3][4];
foo(arr1);
foo(arr2);
foo(arr3);
}
活生生的例子。