Reputation: 797
I am new in using C++ templates. I need to write a template function specialization for my project. It is a simple Sum function for different type inputs and it calculates the sum between two iterators. The original function is generic and so accepts a template argument. The template specialization is written for Maps.
#include <map>
#include <string>
template <typename T>
double Sum(T &it_beg, T &it_end) {
double sum_all = 0;
for(it_beg++; it_beg != it_end; it_beg++)
sum_all += *it_beg;
return sum_all;
};
template <>
double Sum(std::map<std::string, double> &it_beg, std::map<std::string, double> &it_end) {
double sum_all = 0;
for(it_beg++; it_beg != it_end; it_beg++)
sum_all += it_beg->second;
return sum_all;
};
when I try to run the code, I get the following errors
...\sum.h(21): error C2676: binary '++' : 'std::map<_Kty,_Ty>' does not define this operator or a conversion to a type acceptable to the predefined operator
1> with
1> [
1> _Kty=std::string,
1> _Ty=double
1> ]
I appreciate if anyone could give me a hint ! thanks
Upvotes: 1
Views: 174
Reputation: 19607
Your function signature should look like this (possibly without references) so you can pass in rvalues (iterators are cheap to copy anyway):
template <>
double Sum(std::map<std::string, double>::iterator it_beg,
std::map<std::string, double>::iterator it_end)
std::map
does not define operator++
, clearly your arguments are meant to be std::map::iterator
s.
Don't forget to remove the references from the main template function parameters too.
There's also this:
for(it_beg++; it_beg != it_end; it_beg++)
Why are you incrementing it_beg
as you enter the loop? You can leave initialization statement empty.
Upvotes: 1