c++ - error C2783 无法推断模板参数

标签 c++ templates

我被这个错误困住了。 我也找到了一个解决方法,但它有点扼杀了锻炼的全部目的。

我正在尝试创建一个函数,它将使用两个指向同一个容器的迭代器。我会找到它们之间的元素总和。我为像 vector 这样的顺序容器创建了通用函数,它工作正常。我为关联容器重载了相同的函数。这是给出错误的地方。

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\my documents\visual studio 2010\projects\demo.cpp(41): error C2783: 'double Sum(const std::map::const_iterator &,const std::map: :const_iterator &)' : 无法推断出 'T1' 的模板参数

解决方法:

如果将 call 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)

类型 T1T2不能从调用处的参数中推导出来。这在标准中是这样定义的,如果你考虑一下(在一般情况下)它是有道理的。

考虑用 std::map<>::const_iterator 代替你有sometemplate<T>::nested_type调用地点的参数是 int .如果编译器必须推导类型,它必须实例化 sometemplate对于所有可能的类型 T在宇宙中(无限集)并找到其中的嵌套类型 nested_typeint 的类型定义.

正如有人在评论中指出的那样,您可以更改模板,而不是在映射的键和值类型上进行模板化,它只采用迭代器。


委托(delegate)值的提取

这是提供 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 简单得多。模板。

关于c++ - error C2783 无法推断模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573331/

相关文章:

c++ - 如何像资源管理器一样在 ListView 中显示缩略图?

c++ - 以有限的生命周期运行 .exe?

c++ - 具有 map<value, key> 和原子操作的 CUDA

javascript - 我如何将数据从 Django 模板传递到 Angular 4?

c++ - C++ 中的非类型模板参数可以使用大括号初始值设定项吗?

c++ - 多个来源的模板实现

c++ - 模板推导失败,参数包后有参数

c++ - 关于字符串操作

c++ - 使用来自不同文件的命名空间成员

c++ - 如何修复: Executing lambda expression using pthread in c++