下面的代碼對我來說工作正常。在C++中通過引用傳遞數組模板函數
#include <iostream>
using namespace std;
template<class T>
T sum_array(T (&a)[10], int size)
{
T result=0;
for(int i=0; i<size; i++)
{
result = a[i] + result;
}
return result;
}
int main()
{
int a[10] = {0,1,2,3,4,5,6,7,8,9};
cout<<sum_array(a, 10)<<endl;
double d[10] = {1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1};
cout<<sum_array(d, 10)<<endl;
cin.get();
}
但如果儘量讓我的功能更通用的如功能圖所示,它提供了錯誤說沒有函數模板實例中移除數組大小。
template<class T>
T sum_array(T (&a)[], int size)
{
T result=0;
for(int i=0; i<size; i++)
{
result = a[i] + result;
}
return result;
}
在同一時間,如果我刪除參考如下所示,它只是工作正常。
template<class T>
T sum_array(T a[], int size)
{
T result=0;
for(int i=0; i<size; i++)
{
result = a[i] + result;
}
return result;
}
我是比較新的模板可以請你解釋上述行爲。
可能最好是使用'的std ::陣列'對於這種情況 –