【发布时间】:2013-11-23 14:22:42
【问题描述】:
下面的代码对我来说很好。
#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::array<double>