首页 > 解决方案 > 没有匹配函数调用“...”涉及模板化函数的编译器错误

问题描述

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

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

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)

标签: c++functiontemplates

解决方案


是的*,你的参数是问题所在。迭代器不是指针,而是旨在模仿指针(另一方面,指针可以是有效的迭代器)。不要通过指针传递迭代器,而是通过值传递它们,例如:

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

推荐阅读