没有匹配函数调用 "..." 涉及模板化函数的编译器错误

No matching function for call to "..." Compiler errors involving templated functions

本文关键字:函数 错误 编译器 函数调用      更新时间:2024-09-26

我正在进行一个项目,在这个项目中,我制作了各种算法,如整数的计数和排序,然后我将它们转换为模板函数,以便它们可以与向量和列表等一起使用。

例如,一个模板化函数如下所示:

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";