2015-08-29 156 views
1

我是使用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>   ] 

我很感激,如果任何人都可以給我一個提示! 感謝

+0

你的for-loops有些問題。 – erip

+0

後綴定義增量運算符沒有爲std :: map定義std :: string,double>您的參數類型應該是std :: map :: iterator以使增量工作。 –

+0

是的。我只注意到了這一點。謝謝你的評論。 – Hamed

回答

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::iterator s。

不要忘記從主模板函數參數中刪除引用。

還有這個:

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

你爲什麼遞增it_beg當你進入循環?您可以將初始化語句留空。

+0

謝謝!這真的有幫助。還有一個問題,當我嘗試通過創建cpp文件來分離實現時,出現鏈接器錯誤!當我將所有內容包含在hpp中時,它都能正常工作,但是一旦我創建了cpp,就會出現鏈接錯誤(顯然,在這種情況下,我在主程序中包含了cpp文件)。你有什麼想法?再次感謝。 – Hamed

+0

[模板只能在頭文件中實現](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)。 – LogicStuff

+0

非常感謝! – Hamed