Kev*_*ARD 0 c++ const argument-passing multidimensional-array
关于将数组作为const参数传递的问题,我试图弄清楚如何编写一个方法,其中参数是一个固定大小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
}
Run Code Online (Sandbox Code Playgroud)
此解决方案中唯一的问题是我们不知道第一个维度.有人有解决方案吗?
提前致谢,
凯文
[编辑]
我不想使用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
Run Code Online (Sandbox Code Playgroud)
如果在运行时未知任何维度,则可能需要动态分配数组.在这种情况下,请考虑使用std::vector两者来管理分配的内存并跟踪大小.