没有匹配函数调用 "..." 涉及模板化函数的编译器错误
No matching function for call to "..." Compiler errors involving templated functions
我正在进行一个项目,在这个项目中,我制作了各种算法,如整数的计数和排序,然后我将它们转换为模板函数,以便它们可以与向量和列表等一起使用。
例如,一个模板化函数如下所示:
template<typename Iter>
int count(Iter* first, Iter* limit, int value)
{
int counter = 0;
while(first != limit)
{
if(*first == value)
++counter;
++first;
}
return counter;
}
当我在main.cpp
中运行一些代码时,例如:
std::vector<int> a = {0, 0, 2, 4, 2, 0};
//I expect count to return 3 for this call...
cout << count(a.begin(), a.end(), 0) << "n";
它给了我一个编译器错误:
error: no matching function for call to ‘count(std::vector<int>::iterator, std::vector<int>::iterator, int)’
cout << count(a.begin(), a.end(), 0) << "n";
我真的试过自己解决这个问题,但这对我来说没有意义。我有另一种算法print
,它可以打印从vec.begin()
到vec.end()
的矢量,效果非常好。我试着在有效的和无效的之间建立联系,但对我来说没有任何逻辑意义
跟进:可能是我的函数定义中的*
有问题吗??也许是因为我有(Iter *first, Iter *last)
而不是(Iter first, Iter last)
?
是的,参数中的*
就是问题所在。迭代器不是指针,而是被设计为模仿指针(另一方面,指针可以是有效的迭代器(。不要按指针传递迭代器,而是按值传递,例如:
template<typename Iter>
int count(Iter first, Iter limit, int value)
{
int counter = 0;
while (first != limit)
{
if (*first == value)
++counter;
++first;
}
return counter;
}
附带说明一下,标准C++库已经有了std::count()
算法,它与count()
函数做的事情相同:
#include <vector>
#include <algorithm>
std::vector<int> a = {0, 0, 2, 4, 2, 0};
cout << std::count(a.begin(), a.end(), 0) << "n";
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- C++ OpenCV 卡尔曼滤波器构造函数错误
- C++:用户定义的显式类型转换函数错误
- C++ 合并字符串以'system'函数错误
- C++ wmain 函数错误时使用 Unicode
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- C++ 中常量属性的初始化构造函数错误
- 线程 std::调用未知类型,无法专门化函数错误
- 表单显示对话框函数错误,并且不执行下面的语句
- 函数错误 C2059:语法错误:'>'不起作用
- STL向量上出现奇怪的复制构造函数错误
- C++ Visual Studio 重载函数错误:没有重载函数的实例与指定的类型匹配
- C++引用已删除函数错误
- 为什么通过带有文字编号的引用调用会出现"无匹配函数"错误?
- C++ 乘法定义的构造函数错误消息似乎错误
- 在 c++ 代码中将数组传递给函数错误
- FFMPEG avcodec_decode_video2函数错误代码
- 为什么我会收到转换函数错误