I am stuck with this error . I have found a workaround too but it kind of kills the whole purpose of exercise.
I am trying to create a function which will take two iterators pointing to same container . I will find the sum of elements between them. I created general function for the sequential containers like vector which works fine. I overloaded the same function for associative containers. This is the one giving error.
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;
}
Compilation error is: 1>c:\documents and settings\ABC\my documents\visual studio 2010\projects\demo.cpp(41): error C2783: 'double Sum(const std::map::const_iterator &,const std::map::const_iterator &)' : could not deduce template argument for 'T1'
Workaround:
If call Sum(iter1,iter2) is replaced with Sum < string,double > (iter1,iter2), it compiles fine.
Was I trying to do something impossible as per C++ standards in the first place?