I want to create a Sum() function that calculates the sum of a STL container. The function uses the template argument for the iterator type and accepts two iterators as arguments as below:
template <typename T>
double Sum(typename T::const_iterator start, typename T::const_iterator end)
{
typename T::const_iterator i3;
double sum2=0.0;
for (i3=start; i3 != end; ++i3)
{
sum2 += (i3);
}
return sum2;
}
and in the main() I call the function like:
vector<double>::const_iterator vec_start=myvector.begin();
vector<double>::const_iterator vec_end=myvector.end();
cout<<"The sum of the vector is "<<Sum(vec_start, vec_end)<<endl;
But it says that no matching function call for Sum(). I read some discussions that it's because the function signature is T but I pass iterators and that I need to specify data type before passing iterator parameters.
Just as the discussions you've found said, the template parameter T
can't be deduced automatically because of non-deduced contexts , so you need to specify it explicitly. eg
cout << "The sum of the vector is " << Sum<vector<double>>(vec_start, vec_end) << endl;
// ~~~~~~~~~~~~~~~~
But you don't need to do that in fact, you could change the declaration of Sum
to:
template <typename I>
double Sum(I start, I end)
{
I i3;
double sum2=0.0;
for (i3=start; i3 != end; ++i3)
{
sum2 += *i3;
}
return sum2;
}
I
could be deduced then it's fine to use it originally as
cout << "The sum of the vector is " << Sum(vec_start, vec_end) << endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.