1

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

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Hamed
  • 757
  • 3
  • 10
  • 17

1 Answers1

1

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::iterators.

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • Thanks ! That really helps. Just one more question, when I try to separate the implementation by creating cpp file, I get a linker error !! It works perfectly when I include everything in hpp but as soon as I create cpp I get the link error ( obviously in this case I include cpp file in the main program). You have any idea? Thanks again. – Hamed Aug 29 '15 at 22:22
  • [Templates can be implemented only in header file](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – LogicStuff Aug 29 '15 at 22:25
  • I read that post and followed their guides but still I have problem separating the header from implementation. I created another post since it may be of interest for other people. http://stackoverflow.com/questions/32292476/c-template-specialization-linker-error Thanks for your help anyway. – Hamed Aug 30 '15 at 02:02
  • @Hamed You shouldn't separate them. That's what I tried to tell you. – LogicStuff Aug 30 '15 at 09:27