简体   繁体   English

C ++模板函数专业化错误

[英]C++ Template Function specialization error

I am new in using C++ templates. 我是使用C ++模板的新手。 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. 模板专长是为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 谢谢

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. std::map没有定义operator++ ,显然您的参数是std::map::iterator

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? 为什么在进入循环时增加it_beg You can leave initialization statement empty. 您可以将初始化语句留空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM