带有比较函数的C++ <unresolved重载函数类型>

use*_*171 1 c++ comparison search templates

我正在尝试实现自定义二进制搜索以运行日期向量.

我的二进制搜索功能如下:

template <typename RandomAccessIterator, typename Value, typename Comparer>
inline int binary_search(RandomAccessIterator const  first, RandomAccessIterator const  last, Value const& value, Comparer comparer)
{
    RandomAccessIterator it(std::lower_bound(first, last, value, comparer));
    if (it == last || comparer(*it, value) || comparer(value, *it))
      return distance(first,last);

    return distance(first,it);
}
Run Code Online (Sandbox Code Playgroud)

我使用的比较器定义为:

template <class T>
inline bool cmp(T lhs,T rhs)
{
  return lhs<rhs;
}
Run Code Online (Sandbox Code Playgroud)

这两个编译没有问题,但是,当我尝试使用以下代码调用binary_search函数时,我收到编译错误:

binary_search(date_list.begin(),date_list.end(),date2,cmp)
Run Code Online (Sandbox Code Playgroud)

其中date_list是包含日期的向量,date2是一个int.

确切的错误消息是:

error: no matching function for call to ?binary_search(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int&, <unresolved overloaded function type>)?
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题的任何想法?

Joh*_*eek 5

cmp在C++需要值的上下文中传递template()的名称.除了你不能这样做的事实,这是一个鸡或蛋问题:什么类型cmp?函数的类型取决于其参数,此函数可以接受任何类型的参数.那么编译器推断出模板参数的类型是什么Comparer?它必须查看函数的主体以找出您期望的int,并且这并不总是可行的 - 编译器并不总是能够访问模板的源代码.

您需要专门选择要传递的函数模板的类型.例如:

binary_search(date_list.begin(), date_list.end(), date2, cmp<int>);
Run Code Online (Sandbox Code Playgroud)