There is no suitable function for "f (int [4] [4])" when using the template "void f (int x [M] [N])"?
#include <iostream>
template <int M, int N>
void print1(int src[M][N]) { }
void print2(int src[4][4]) { }
int main() {
int src[][4] = {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
};
print1(src);
// gives error
// error: no matching function for call to 'print1(int [4][4])'
print2(src);
// works!
}
In the above code, it print2()works as expected, but print1()gives me an error
error: there is no corresponding function to call "print" (int [4] [4]) '
I don’t understand, they look exactly the same, I just replaced the hard-coded values to use patterns so that it can accept arrays of any size.
Why is this not working? What am I doing wrong?
In ad
void print2(int src[4][4])
The first 4does not make sense. This function is the same as if you declared it as
void print2(int src[][4])
or
void print2(int (*src)[4])
, C ++. , , . , " T", " T". , C ++ .
, :
template <int M, int N>
void print1(int src[M][N])
print2, :
template <int M, int N>
void print1(int src[][N])
, , , M N . M , . , :
print1<4, 4>(src)
, N; M, . , M N:
print1<4>(src)
:
template <int M, int N>
void print1(int (&src)[M][N])
. ? , " int". " int". () , .
, . , , .
, , int.
You can force the compiler to output type arguments, but you cannot force the compiler to take information from your type (in this case, the size of the array) and output the whole parameters of the template.
For example, this works because the compiler infers the type as int [4] [4].
template <class T>
void printFoo(T t)
{
}
and using this template, how this of course works:
print1<4,4>(src);