[英]error C2783 Could not deduce template arguments
我被這個錯誤所困擾。 我也找到了一種解決方法,但它卻扼殺了鍛煉的全部目的。
我試圖創建一個函數,它將使用兩個指向相同容器的迭代器。 我會發現它們之間元素的總和。 我為向量之類的順序容器創建了通用功能,效果很好。 我為關聯容器重載了相同的功能。 這是一個錯誤。
map<string,double> myMap;
myMap["B"]=1.0;
myMap["C"]=2.0;
myMap["S"]=3.0;
myMap["G"]=4.0;
myMap["P"]=5.0;
map<string,double>::const_iterator iter1=myMap.begin();
map<string,double>::const_iterator iter2=myMap.end();
cout<<"\nSum of map using the iterator specified range is: "<<Sum(iter1,iter2)<<"\n";
//Above line giving error. Intellisense is saying: Sum, Error: no instance of overloaded function "Sum" matches the argument list.
//function to calculate the sum is listed below (It appears in a header file with <map> header included):
template <typename T1,typename T2>
double Sum(const typename std::map<T1,T2>::const_iterator& input_begin,const typename std::map<T1,T2>::const_iterator& input_end)
{
double finalSum=0;
typename std::map<T1,T2>::const_iterator iter=input_begin;
for(iter; iter!=input_end; ++iter)
{
finalSum=finalSum+ (iter)->second;
}
return finalSum;
}
編譯錯誤為:1> c:\\ documents and settings \\ ABC \\ mydocuments \\ visual studio 2010 \\ projects \\ demo.cpp(41):error C2783:'double Sum(const std :: map :: const_iterator&,const std :: map :: const_iterator&)':無法推斷出“ T1”的模板參數
解決方法:
如果將調用Sum(iter1,iter2)替換為Sum <string,double>(iter1,iter2),則編譯良好。
我是否首先嘗試按照C ++標准做一些不可能的事情?
在以下模板中,該錯誤實際上很明顯:
template <typename T1,typename T2>
double Sum(const typename std::map<T1,T2>::const_iterator& input_begin,
const typename std::map<T1,T2>::const_iterator& input_end)
T1
和T2
類型不能從調用位置的參數推導出。 在標准中對此進行了定義,如果您考慮一下(通常情況下),這是有道理的。
考慮到不是std::map<>::const_iterator
而是使用了sometemplate<T>::nested_type
並且調用位置的參數是int
。 如果編譯器必須推斷出類型,則必須為sometemplate
中的所有可能類型T
(無限集)實例化一個sometemplate
,並找出嵌套類型nested_type
是int
的typedef對於它們中的nested_type
一個。
正如有人在注釋中指出的那樣,您可以更改模板,這樣就不必使用映射的鍵和值類型作為模板,而只需使用迭代器即可。
委托提取價值
這是提供單一Sum
實現的解決方法,該實現可以處理順序容器和關聯容器。
namespace detail {
template <typename T> T valueOf( T const & t ) { return t; }
template <typename K, typename V>
V valueOf( std::pair<const K, V> const & p ) {
return p.second;
}
}
template <typename Iterator>
double Sum( Iterator begin, Iterator end ) {
double result = 0;
for (; begin != end; ++begin) {
result += detail::valueOf(*begin);
}
return result;
}
我沒有測試代碼,但是應該這樣做。 這可能比在Sum
模板上使用SFINAE更為簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.