我正在學習STL和模板。這是我的問題。我寫這個函數的兩個迭代器「之間」計算元素的總和:STL容器的C++函數模板專業化
template <typename Iter> double PartialSum(Iter itBegin, Iter itEnd){
if (itBegin == itEnd) return 0.;
double dSum = 0;
while(itBegin != itEnd){
dSum += (*itBegin);
++itBegin;
}
return dSum;
}
而且這工作正常(我知道我可以使用std::accumulate
但這是學習的目的)。現在,我想有相同的功能的std:map
但迭代器有不同的工作比在std::vector
和std::list
的情況。因此,我想寫超載/專用PartialSum
。我嘗試和失敗是這個(小例子):
template <typename T1, typename T2> double PartialSum(std::map<T1,T2>::iterator itBegin{
return 0.;
}
這是錯誤日誌:
Main.cpp(42): error: nontype "std::map<_Key, _Tp, _Compare, _Alloc>::iterator [with _Key=T1, _Tp=T2, _Compare=std::less<T1>, _Alloc=std::allocator<std::pair<const T1, T2>>]" is not a type name template <typename T1, typename T2> double PartialSum(std::map<T1,T2>::iterator itBegin){ Main.cpp(83): error: no instance of overloaded function "PartialSum" matches the argument list argument types are: (std::_Rb_tree_iterator<std::pair<const std::string, int>>) std::cout<<"Map partial sum: "<<PartialSum(myMap.begin())<<std::endl;
由於它是如此簡單,我可能不undersatnd一些非常基本的。會很樂意聽聽你的意見:-)
你不小心刪除一半的線路?您尚未完成專業化的參數編寫。 –
另一方面,你不能部分專門化一個功能。 (這是一個重載,而不是專門化)你應該使用一個模板函數來調用模板類中的一個靜態函數。這可以讓你部分專業化。 –
你是什麼意思*失敗*?編譯錯誤?一些意外的運行時行爲 – Gorpik