-->

模板函数给出“不匹配函数呼叫”错误(Template function gives “no matc

2019-10-16 15:28发布

计算器上的第一个问题:)我是比较新的C ++,并且从未使用过的模板,所以请原谅我,如果我做一些愚蠢的。 我有过的一般类型的指定元素的列表,并检查梳理模板功能。 这样我可以指定是否在寻找一个字符串,或一个int,或什么的。

template <class T>   
bool inList(T match, std::string list)  
{
    int listlen = sizeof(list);
    for (int i = 0; i <= listlen; i++) {
        if (list[i] == match) return true;
        else continue;
    }
    return false;
};

这是我打电话给inList() testvec是用几个元件,其中包括“测试”的字符串向量:

if (inList<string>("test", testvec))
    cout << "success!";
else cout << "fail :(";

令我感到沮丧和困惑,在编译时,我处以以下错误:

error: no matching function for call to 'inList(const char [5], std::vector<std::basic_string<char> >&)'

我在做什么错误? :(

[编辑]我忘了提及的是,模板定义是在全局命名空间。 (这是一个简单的测试程序,看看我的模板将工作,这不,显然是:()

Answer 1:

这是因为没有办法从一个std ::向量转换为std :: string。 相反,你需要做的是一个集合的概念抽象。

你这样做,使人们可以在任何他们想要的集合类型通过。 因为它符合一个集合的“概念”,他们只要能使用数组,向量,字符串,列表,双端队列......(我们也希望C ++ 1X自带的概念!)。 他们甚至可以使用他们自己内部的专门优化集合类型。 这是模板的美感。

使用C ++ 11(与任何标准的集合,原始阵列,和用户定义的类型作品):

template<class elem_t, class list_t>
bool in_list(const elem_t& elem, const list_t& list) {
   for (const auto& i : list) {
      if (elem == i) {
         return true;
      }
   }
   return false;
}

编辑:这是一个非标准扩展来推断的std :: initializer_list作为模板参数,所以提供一个明确的控制装置:

template<class elem_t>
bool in_list(const elem_t& elem, std::initializer_list<elem_t> list) {
   for (const auto& i : list) {
      if (elem == i) {
         return true;
      }
   }
   return false;
}

在这个版本中,你可以这样调用它:

int main() {
   std::vector<int> a = {1, 2, 3, 4, 5};
   std::cout << in_list(3, a) << std::endl;
   std::string b = "asdfg";
   std::cout << in_list('d', b) << std::endl;
   std::cout << in_list('d', "asdfg") << std::endl;
   std::cout << in_list(3, {1, 2, 3, 4, 5}) << std::endl;
   return 0;
}

而对于我们这些仍然在C ++ 98,这会为两个字符串和载体,以及一些用户定义类型的工作。 它不会与原始阵列的工作,虽然。

template<class elem_t, class list_t>
bool in_list_98(const elem_t& elem, const list_t& list) {
   list_t::const_iterator end = list.end(); //prevent recomputation of end each iteration
   for (list_t::const_iterator i = list.begin(); i < end; ++i) {
      if (elem == *i) {
         return true;
      }
   }
   return false;
}

或者,你可以去STL风格:

template<class elem_t, class iterator_t>
bool in_list_stl(const elem_t& elem, iterator_t begin, iterator_t end) {
   for (iterator_t i = begin; i < end; ++i) {
      if (elem == *i) {
         return true;
      }
   }
   return false;
}
//call like std::string s = "asdf"; in_list_stl('s', s.begin(), s.end());

如果我犯了一个错误,对不起,我没有我的编译器现在正在运行...



文章来源: Template function gives “no matching function for call” error