Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do templates work when using them as array dimensions?

I tried to use tempaltes as array dimension value. I was puzzled when tried to specify wrong dimension as tempate argument. For example code:

#include <iostream>

using namespace std;

template <int X, int Y>
void f(int a[X][Y]) {
    for (int i = 0; i < X; ++i) {
        for (int j = 0; j < Y; ++j) {
            cout << a[i][j] << " ";
        }
        cout << '\n';
    }
}

int main() {
    int a[2][2] = {{1, 2}, {3, 4}};
    f<2, 2>(a); // compilation succeeded
    f<10, 2>(a); // compilation succeeded
    f<2, 10>(a); // compilation FAILED
}

Why in the last case compilation fails, but in case <10, 2> it does not?

error: no matching function for call to 'f'
note: candidate function template not viable: no known conversion from 'int [2][2]' to 'int (*)[10]' for 1st argument
like image 959
spectator Avatar asked May 13 '26 18:05

spectator


1 Answers

You get this result because f(int a[X][Y]) is a lie.

Arrays are not first-class citizens in C++. You cannot pass an array as a function parameter by value. So when you write such parameter, it is silently adjusted to a pointer (the first level only). Thus the type of a is really int (*)[Y].

Since there is no X in the type of a, absolutely any X will work.

If you want to enforce both X and Y, try passing the array by reference:

void f(int (&a)[X][Y])

or use std::array.

like image 169
n. 1.8e9-where's-my-share m. Avatar answered May 16 '26 06:05

n. 1.8e9-where's-my-share m.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!