我正在学习 C++,并且正在尝试实现一个二分搜索函数,该函数查找谓词所适用的第一个元素。该函数的第一个参数是一个向量,第二个参数是一个计算给定元素的谓词的函数。二分查找函数如下所示:
template <typename T> int binsearch(const std::vector<T> &ts, bool (*predicate)(T)) {
...
}
如果像这样使用的话,这将按预期工作:
bool gte(int x) {
return x >= 5;
}
int main(int argc, char** argv) {
std::vector<int> a = {1, 2, 3};
binsearch(a, gte);
return 0;
}
但如果我使用 lambda 函数作为谓词,则会收到编译器错误:
search-for-a-range.cpp:20:5: error: no matching function for call to 'binsearch'
binsearch(a, [](int e) -> bool { return e >= 5; });
^~~~~~~~~
search-for-a-range.cpp:6:27: note: candidate template ignored: could not match 'bool (*)(T)' against '(lambda at
search-for-a-range.cpp:20:18)'
template <typename T> int binsearch(const std::vector<T> &ts,
^
1 error generated.
上述错误是由
binsearch(a, [](int e) -> bool { return e >= 5; });
怎么了?为什么编译器不相信我的 lambda 具有正确的类型?