Partita
Partita

Reputation: 215

use of const iterator in template function

I'm using template functions in order that it may work with list or vector of different numerical data types. But one of them has an issue:

// This function should take 2 iterators of a vector/list and sum the elements between them
template <typename T >
double Sum1(typename T::const_iterator start, typename T::const_iterator end){
    double sum = 0;
    // For g++, "typename is needed before T::const_iterator"
    for(typename T::const_iterator I = start; I <= end;I++){
        sum += *I;
    }
    return sum;
}

in the main(), it is called like this:

vector<double> b;// and it is pushed by numbers 1-9 later

cout<<Sum1(b.begin(), b.end())<<endl;

but the compiler gives me errors

no matching function for call to ‘Sum1(std::vector::iterator, >std::vector::iterator)’

couldn't deduce template parameter ‘T’

However, this function works fine:

// T can be vector<int>, list<double>, etc. 
template <typename T >
double Sum(T& values){
    double sum = 0;
    // For g++, "typename is needed before T::const_iterator"
    for(typename T::const_iterator I = values.begin(); I != values.end();I++){
        sum += *I;
    }
    return sum;
}

Any idea why this happens? How should I revise the first function so it can take 2 iterators of a vector/list and calculate the sum in between?

Upvotes: 0

Views: 2312

Answers (1)

John Dibling
John Dibling

Reputation: 101506

Instead of templatizing on the container type, templateize on the iterator. And don't restrict your users to const_iterator -- any iterator should do is you don't actually modify the contents through the iterator:

template <typename Iter> double Sum1(Iter start, Iter end)

By doing this you can also use any type that is dereferenceable and incrementable -- such as a simple pointer.

Upvotes: 4

Related Questions