Extaze
Extaze

Reputation: 1197

Template size multidimensional arrays C++

I would like to use template to specify sizes in functions. Let me give you an example. I can do this:

int sub (int a[2][2]) {

}
int main () {
   int a[2][2];
   sub(a);
}

I can do this:

template<int size2>
int sub (int a[][size2]) {

}
int main () {
   int a[2][2];
   sub(a);
}

But what I would like is this:

template<int size1, int size2>
int sub (int a[size1][size2]) {

}
int main () {
   int a[2][2];
   sub(a);
}

How could I?

Upvotes: 0

Views: 350

Answers (3)

imreal
imreal

Reputation: 10348

As Brian Bi already wrote, the best way to go is to use std::array.

But to answer your question, it is halfway possible to do what you want.

When you use a C-style 2D array as an argument to a function, it decays to a pointer to an array of the second dimension. For example int a[6][6] decays to int (*a)[6], so the first dimension is hidden and means nothing to the compiler. The second dimension however, can be used as template parameters and can be deduced.

For example:

template<int S>
void func(int (*a)[S])
{
    cout << S << endl;
}

and then:

int a[66][67];
func(a);

prints "67".

Upvotes: 0

RamblinRose
RamblinRose

Reputation: 182

Here is another way (sub<2,2>:

template<int size1, int size2>
int sub (int a[size1][size2]) {

}    
void main(int argc, char **argv)
{
    int a[2][2];
    sub<2,2>(a);
}

Upvotes: -1

Brian Bi
Brian Bi

Reputation: 119069

The better option is probably to use std::array, if you have C++11 support, or std::vector, if not. If you really want to use C-style arrays, you can pass them by reference, using the following syntax.

template<size_t size1, size_t size2>
int sub (int (&a)[size1][size2]) {
    // ...
}
int main() {
    int a[2][2];
    sub(a);
}

Upvotes: 7

Related Questions