简体   繁体   中英

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. 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.

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.

The reference prevents line 4 ( inTab = 0; ), because you've made inTab a reference. The const prevents line 5 ( inTab[0] = 0; ) because an inTab pointer is const.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM