[英]const array of fixed size const array as argument of a method in C++
Following my question about passing array as const argument , I am trying to figure out how to write a method where the argument is a const array of fixed size const array. 在我关于将数组作为const参数传递的问题之后,我试图找出如何编写一个参数为固定大小的const数组的const数组的方法。 The only writable thing would be the content of these arrays.
唯一可写的是这些数组的内容。
I am thinking about something like this: 我在想这样的事情:
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
}
The only problem in this solution is that we don't know the first dimension. 此解决方案中的唯一问题是我们不知道第一个维度。 Does anyone have a solution for this?
有人对此有解决方案吗?
Thanks in advance, 提前致谢,
Kevin 凯文
[Edit] [编辑]
I don't want to use std::vector or such dynamically allocated arrays. 我不想使用std :: vector或此类动态分配的数组。
If both dimensions are known at compile time, then you could use a 2-dimensional array (in other words, an array of arrays) rather than an array of pointers to arrays: 如果两个维度在编译时都是已知的,则可以使用二维数组(换句话说,数组的数组),而不是使用指向数组的指针的数组:
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
If either dimension is not known at runtime, then the arrays presumably need to be dynamically allocated. 如果在运行时不知道任何一个维度,则可能需要动态分配数组。 In that case, consider using
std::vector
both to manage the allocated memory and to keep track of the size. 在这种情况下,请考虑使用
std::vector
来管理分配的内存并跟踪大小。
The reference prevents line 4 ( inTab = 0;
), because you've made inTab
a reference. 该引用阻止第4行(
inTab = 0;
),因为您已将inTab
用作引用。 The const prevents line 5 ( inTab[0] = 0;
) because an inTab
pointer is const. const阻止第5行(
inTab[0] = 0;
),因为inTab
指针是const。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.