template

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?

+5
source share
7 answers

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". () , .


, . , , .

+11

:

template <int M, int N>
void print1(int (&src)[M][N])
{
}
+6

, int src[4], int *src. , print2 :

void print2(int (*src)[4]);

, int[4].

template <int M, int N>
void print1(int (*src)[N]) { }

, , , , int[4].

M .

, , :

template <int M, int N>
void print1(int (&src)[M][N]) { }

. , . .

+2

, , .

print1<4,4>(src);

, , (print1<k,m>(src) ).

+1

, , 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);
+1
source

You should pass a template parameter. Like this:

print1<4,4>(src);
0
source

A call to a template function can use the deduction of a template argument for types only. It is not possible to print the arguments of a non-piggy type template.

0
source

All Articles