depecheSoul
depecheSoul

Reputation: 956

Passing a array into a template function

I am trying to make a template function that has a array as parameter. The function retruns sum of the numbers in the array.

This is my code:

template <class var>
var sum_numbers(var array[]) {
    var sum = 0;
    for (int f1=0; array[f1]!='\0'; f1++) {
        sum = sum + array[f1];
    }
    return sum;
}

The function always returns

-2001120059

Can you please give some idea how to improve my code, and can you please give me some reference where to find more information about templates?

Thank you very much.

UPDATE: My input, and function call:

int a[] = {1,2,3,4,5};
cout << sum_numbers(a) << endl;

Upvotes: 2

Views: 1543

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

Your code seems to expect that the array is zero terminated. No such thing is guaranteed. That only happens with string literals. Your function doesn't actually take an array, it takes a pointer. You can't take an array by value, but if you want to take one by reference, you can do this:

template <class var, size_t N>
var sum_numbers(var (&array)[N]) {
    var sum = 0;
    for (size_t f1=0; f1<N; f1++) {
        sum = sum + array[f1];
    }
    return sum;
}

Or, more succinctly:

template<typename T, size_t N>
T sum_numbers(T (&arr)[N]) {
    return std::accumulate(arr, arr + N, T());
}

Or, if you want to go completely general, and have good support for C++11:

template<typename C>
auto sum_numbers(C const & c)
    -> typename std::remove_reference<decltype(*std::begin(c))>::type
{
    typedef typename std::remove_reference<decltype(*std::begin(c))>::type value_type;
    return std::accumulate(std::begin(c), std::end(c), value_type());
}

can you please give me some reference where to find more information about templates?

See the intermediate and advanced books in [this list]. Even the beginner books should at least give you an introduction to them.

Upvotes: 11

Related Questions