What do parameters of this function mean? Could somebody show an example of how to call this function?
template<int N, int K> void poly_multiply(int (*p1)[N], int (*p2)[K], int (*p3)[N+K-1]){
}
What do parameters of this function mean? Could somebody show an example of how to call this function?
template<int N, int K> void poly_multiply(int (*p1)[N], int (*p2)[K], int (*p3)[N+K-1]){
}
int (*p1)[N]
p1
is a pointer to an array of N ints. Unlike normal "array" parameters, such as these:
void foo(int arr[], int arr2[10])
the type (including the size) of the array is preserved. It does not degrade to a pointer to int. You can also have references to arrays:
int (&r1)[N]
int (&r2)[N+K-1]
A declaration of the form int (*p)[N]
means p
is a pointer to an array of N ints. Reading of such declarations is tricky - you start with the identifier then go to the right and jump to the left when there's nothing more, while obeying the precedence that the parentheses introduce. Google "spiral rule" for more info. Here's another way to read declarations (the answer by James Kanze).
An example:
template<int N, int K>
void poly_multiply(int (*p1)[N], int (*p2)[K], int (*p3)[N+K-1])
{
}
int a[5]; // N = 5
int b[10]; // K = 10
int c[14]; // 10+5-1 = 14
poly_multiply(&a, &b, &c);
Because poly_multiply
is a function template, it lets you pass pointers of arrays of any size, as long as the size of third array adds up to N+K-1 - else the compiler will give you an error. The sizes N and K will be automaticaly deduced (unless you choose to specify the template arguments explicitly).
Note that you need to take the adress of the array and can't call the function like poly_multiply(a,b,c);
because in that case the arrays would decay to pointer to the first element (int*
) and the function wouldn't be a match.
template<int N, int K>
void poly_multiply(int (*p1)[N], int (*p2)[K], int (*p3)[N+K-1]);
Has three parameters:
A pointer to an array of N
int
s
A pointer to an array of K
int
s
A pointer to an array of N+K-1
int
s
Note that the latter is a non-deduced context. That means that neither N
nor K
will be deduced for the last argument of the call - thus the type of the last parameter of the specialization solely depends on the types of the first two arguments of the call.
Example:
int arr1[2];
int arr2[3];
int arr3[4];
poly_multiply(&arr1, &arr2, &arr3);
poly_multiply(&arr1, &arr2, &arr2); // Error! Pointer to int[3] cannot be
// converted to pointer to int[4]