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

时间:2012-07-24 09:28:01

标签: c++ multidimensional-array const argument-passing

在我关于passing array as const argument的问题之后,我试图弄清楚如何编写一个方法,其中参数是一个固定大小const数组的const数组。唯一可写的东西就是这些数组的内容。

我正在考虑这样的事情:

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
}

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

提前致谢,

凯文

[编辑]

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

2 个答案:

答案 0 :(得分:5)

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

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来管理分配的内存并跟踪大小。

答案 1 :(得分:0)

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