我被这个错误困住了。,我也找到了一个解决办法,但它有点扼杀了锻炼的全部目的。--
我正在尝试创建一个函数,它将使用两个指向同一个容器的迭代器。我会找到它们之间的元素之和。我为序列容器创建了通用函数,比如向量,它工作得很好。对于关联容器,我重载了相同的函数。这是一个给错误。
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和设置\ABC\my documents\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++标准做一些不可能做到的事情?
发布于 2012-11-26 21:30:00
实际上,在以下模板中,错误非常明显:
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
,并查找嵌套类型nested_type
中的哪种类型是类型为nested_type
到int
的类型。
正如有人在注释中指出的那样,您可以更改模板,而不是在映射的键和值类型上进行模板化,而只需使用迭代器。
委托提取值
这是一种解决方法,可以提供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要简单得多。
https://stackoverflow.com/questions/13573331
复制相似问题