Search code examples
c++templatesdefault-valuedefault-constructorfunction-declaration

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.

What is the meaning of the above line in bold?

How to have a default constructor of T?


Solution

  • It means something like the following

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

    where the default value of the fourth parameter is created using the default constructor of the type T.