我写了这段代码,如果我取消注释倒数第二行,就会出现错误:“模板参数推断/替换失败:”。这是因为C++中的通用函数有一些限制吗?此外,我的程序不会打印数组b
的浮点答案。我能做些什么呢?(抱歉在单个帖子中提出两个问题。)
#include <iostream>
using namespace std;
template <class T>
T sumArray( T arr[], int size, T s =0)
{
int i;
for(i=0;i<size;i++)
{ s += arr[i];
}
return s;
}
int main()
{
int a[] = {1,2,3};
double b[] = {1.0,2.0,3.0};
cout << sumArray(a,3) << endl;
cout << sumArray(b,3) << endl;
cout << sumArray(a,3,10) << endl;
//cout << sumArray(b,3,40) << endl; //uncommenting this line gives error
return 0;
}
编辑1:将40更改为40.0后,代码可以正常工作。这是我得到的输出:
6
6
16
46
我仍然没有在第二个案例中得到浮点答案。有什么建议吗?
b
中推断出double
类型,从40
中推断出int
类型。它不会通过转换来猜测类型,并可能编译错误。可以轻松地让它在推断类型时忽略参数。 - chris