【发布时间】:2021-12-06 14:16:24
【问题描述】:
我对 C++ 中的模板参数推导有疑问。 我不知道为什么下面的示例不起作用。 样本:
#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;
}
编译器打印这个错误:
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);
我发现如果我通过引用传递参数,代码就会起作用,所以函数签名变成这样:
void PrintArray(const int (&arr)[n])
但是为什么呢?您能否解释一下为什么当数组按值传递时,编译器无法预测第一个样本中的数组大小?
【问题讨论】:
标签: c++ arrays templates pass-by-reference pass-by-value