小编Nav*_*een的帖子

通过引用传递数组到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();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果尝试通过删除函数如下所示的数组大小使我的函数更通用,则会出现错误,提示没有函数模板实例。

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;
}
Run Code Online (Sandbox Code Playgroud)

同时,如果我删除了如下所示的引用,它也可以正常工作。

template<class T>
T sum_array(T a[], int size) …
Run Code Online (Sandbox Code Playgroud)

c++ templates

3
推荐指数
1
解决办法
3330
查看次数

标签 统计

c++ ×1

templates ×1