使用 T 的默认构造函数作为默认初始值

Use the default constructor of T for the default initial value

Write a function template that takes a single type parameter (T) and accepts four function arguments: an array of T, a start index, a stop index (inclusive), and an optional initial value. The function returns the sum of all the array elements in the specified range and the initial value. Use the default constructor of T for the default initial value. Repeat the exercise but use explicit to manually create specializations for int data type.

上面加粗的一行是什么意思?

如何获得T的默认构造函数?

大概是下面的意思

template <typename T>
T sum( const T a[], size_t start, size_t stop, const T &init = T() );

其中第四个参数的默认值是使用T.

类型的默认构造函数创建的
#include<iostream>

using namespace std;


template <class T>
T sum(T arr[], int start , int end,T init=T())
{
    T total=init;
    for(int i=start;i<=end;i++)
    {
        total+=arr[i];
    }

    return total;

}

int main()
{
    

    float arr[]={1.0,2.0,3.0,5.0,55.0};
    float result=sum(arr,0,4);
    cout<<"Total : "<<result<<endl;
    return 0;
}