通过引用传递数组到C ++中的模板函数
下面的代码对我来说很好用.
The below code just works fine for me.
#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();
}
但是,如果尝试通过删除函数如下所示的数组大小使我的函数更通用,则会出现错误,提示没有函数模板实例.
But if try to make my function more generic by removing the array size as shown below in function it gives a error saying no instance of function template.
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;
}
如果同时删除如下所示的引用,它也可以正常工作.
At the same time if i remove the reference as shown below it just works fine.
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;
}
我对模板还比较陌生,能否请您解释上述行为.
I am relatively new to templates can you please explain the above behavior.
在函数参数中, []
(内部无维)只是指针的备用语法,因为当以下情况时数组会衰减为指针传递给函数,除非它们通过引用传递.
In funciton parameters, []
(without a dimension inside) is just alternate syntax for a pointer, as arrays decay to pointers when passed into functions, unless they're passed by reference.
这意味着您工作的通用模板(具有 T a []
的模板)与 T a *
完全相同.如果无论如何都要在运行时传递大小,则一切都很好,您可以使用它(它可以用于未声明为数组的其他内容,例如 std :: string :: c_str的返回值()
).
This means that your working generalised template (the one with T a[]
), is exactly the same as T a*
. If you're passing the size in at runtime anyway, all is fine and you can just use that (and it will work for other things not declared as arrays, such as the return value of std::string::c_str()
).
但是,如果您想对临时模板进行泛化但仍将其限制在实际数组中,则可以执行以下操作:
However, if you want to generalise the tempalte but still keep it limited to actual arrays, you can do this:
template<class T, size_t N>
T sum_array(T (&a)[N], int size)
{
T result=0;
for(int i=0; i<size; i++)
{
result = a[i] + result;
}
return result;
}
那样,只能传入一个真正的数组,但是会推导其类型 T
和长度 N
.根据您的用例,在这种情况下,您可能会删除 size
参数.
That way, only a genuine array can be passed in, but both its type T
and its length N
will be deduced. Depending on your use case, you might get away with removing the size
parameter in such case.