I have an issue with template arguments deduction in C++. I don't know why the sample below doesn't work. The sample:
#include <iostream>
template<size_t n>
void PrintArray(const int arr[n]) {
for (int i = 0; i < n; i++)
printf("%d\n", arr[i]);
}
int main() {
int arr[5] = {1, 2, 3, 3, 5};
PrintArray<>(arr);
return 0;
}
The compiler print this error:
main.cpp: In function 'int main()':
main.cpp:12:21: error: no matching function for call to 'PrintArray(int [5])'
PrintArray<>(arr);
^
main.cpp:4:6: note: candidate: template<unsigned int n> void PrintArray(const int*)
void PrintArray(const int arr[n]) {
^~~~~~~~~~
main.cpp:4:6: note: template argument deduction/substitution failed:
main.cpp:12:21: note: couldn't deduce template parameter 'n'
PrintArray<>(arr);
I've found out that the code becomes working if I pass the argument by reference, so the function signature becomes like this:
void PrintArray(const int (&arr)[n])
But why? Could you please explain me why the compiler can't predict the array size in the first sample, when the array is passed by value?