我编写了以下函数,它在 vector 中搜索并找到指针在 vector 中的位置,如果找到成功,则返回迭代器:
template<class InputIterator>
InputIterator MainCore::findDeviceAccordingToIP ( const char * value )
{
std::vector<Device *>::iterator first,last;
first = this->devList->begin();
last = this->devList->end();
Device *temp;
for ( ;first!=last; first++){
temp = *first;
if ( strcmp(temp->endpoint->IPAddress.c_str(),value) == 0)
{
return first;
break;
}
}
//return false;
}
上面cpp文件中的代码我把下面的代码放在*.h文件的MainCore类中:
template<class InputIterator>
InputIterator findDeviceAccordingToIP (const char *value );
现在当我调用另一个函数时,例如:
this->findDeviceAccordingToIP("192.168.2.11");
现在我有两个问题:
编译时出现如下错误:
错误:没有匹配函数调用 MainCore::findDeviceAccordingToIP(const char [13])
我如何获得返回 T 以及 bool 值和迭代器?
最佳答案
关于问题1,函数模板的模板参数对函数参数没有依赖,所以需要显式指定类型:
this->findDeviceAccordingToIP<SomeIteratorType>("192.168.2.11");
此外,模板代码应该在头文件中或头文件包含的文件中。它必须直接或间接地包含在客户端代码中。
请注意,您可以将整个函数替换为对 std::find_if 的调用和一个合适的仿函数。
关于问题2,不清楚你的意思。
关于c++ - 如何在类主体中调用模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11864088/