关于stackoverflow的第一个问题:)我是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
是一个包含一些元素的字符串 vector ,包括“test”: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> >&)'
我做错了什么? :(
[编辑]
我忽略了提及模板定义在全局 namespace 中。 (这是一个简单的测试程序,用于查看我的模板是否可以正常工作,显然它::)无效。
最佳答案
这是因为无法将std::vector转换为std::string。相反,您需要做的是抽象集合的概念。
您这样做是为了使人们可以传递他们想要的任何集合类型。他们可以使用数组, vector ,字符串,列表,双端队列...,只要它适合集合的“概念”(这就是希望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的我们来说,这对于字符串和 vector 以及某些用户定义的类型均适用。它不适用于原始数组。
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());
如果我犯了一个错误,对不起,我现在没有正在运行我的编译器...
关于c++ - 模板函数给出 “no matching function for call”错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10369464/