我是使用C++模板的新手。 我需要爲我的項目編寫模板功能專業化。 對於不同類型的輸入它是一個簡單的Sum函數,它計算兩個迭代器之間的和。原始函數是通用的,因此接受模板參數。模板專業化是爲地圖編寫的。C++模板功能專業化錯誤
#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> ]
我很感激,如果任何人都可以給我一個提示! 感謝
你的for-loops有些問題。 – erip
後綴定義增量運算符沒有爲std :: map定義std :: string,double>您的參數類型應該是std :: map :: iterator以使增量工作。 –
是的。我只注意到了這一點。謝謝你的評論。 – Hamed