固定大小的常量数组的常量数组作为C++中方法的参数

const array of fixed size const array as argument of a method in C++

本文关键字:常量 数组 C++ 方法 参数      更新时间:2023-10-16

继我关于将数组作为常量参数传递的问题之后,我正试图弄清楚如何编写一个方法,其中参数是固定大小的常量数组的常量数组。唯一可写的内容就是这些数组的内容。

我在想这样的事情:

template <size_t N>
void myMethod(int* const (&inTab)[N])
{
    inTab = 0;       // this won't compile
    inTab[0] = 0;    // this won't compile
    inTab[0][0] = 0; // this will compile
}

这个解决方案中唯一的问题是我们不知道第一个维度。有人能解决这个问题吗?

提前感谢

Kevin

[编辑]

我不想使用std::vector或这样的动态分配数组。

如果在编译时两个维度都已知,那么您可以使用二维数组(换句话说,数组数组),而不是指向数组的指针数组:

template <size_t N, size_t M>
void myMethod(int (&inTab)[N][M])
{
    inTab = 0;       // this won't compile
    inTab[0] = 0;    // this won't compile
    inTab[0][0] = 0; // this will compile
}
int stuff[3][42];
myMethod(stuff); // infers N=3, M=42

如果其中一个维度在运行时未知,那么可能需要动态分配数组。在这种情况下,考虑使用std::vector来管理分配的内存和跟踪大小。

引用阻止第4行(inTab = 0;),因为您已将inTab作为引用。const阻止第5行(inTab[0] = 0;),因为inTab指针是const。