C++ 模板函数特化错误

C++ Template Function specialization error

我是 C++ 模板的新手。 我需要为我的项目编写一个模板函数专业化。 它是一个用于不同类型输入的简单 Sum 函数,它计算两个迭代器之间的总和。原始函数是通用的,因此接受模板参数。模板专业化是为地图编写的。

#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;
};

当我尝试 运行 代码时,出现以下错误

...\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>          ]

如果有人能给我提示,我将不胜感激! 谢谢

你的函数签名应该看起来像这样(可能没有引用)所以你可以传入右值(无论如何复制迭代器都很便宜):

template <>
double Sum(std::map<std::string, double>::iterator it_beg,
           std::map<std::string, double>::iterator it_end)

std::map 没有定义 operator++,显然你的论点是 std::map::iterators.

别忘了也从主模板函数参数中删除引用。

还有这个:

for(it_beg++; it_beg != it_end; it_beg++)

为什么在进入循环时递增 it_beg?您可以将初始化语句留空。