C ++ <unresolved overloaded =“”function =“”type =“”> with comparison function </unresolved>

时间:2012-07-08 03:50:39

标签: c++ templates search comparison

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

我的二元搜索功能如下:

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);
}

我使用的比较器定义为:

template <class T>
inline bool cmp(T lhs,T rhs)
{
  return lhs<rhs;
}

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

binary_search(date_list.begin(),date_list.end(),date2,cmp)

其中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>)?

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

1 个答案:

答案 0 :(得分:5)

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

您需要专门选择要传递的功能模板的类型。例如:

binary_search(date_list.begin(), date_list.end(), date2, cmp<int>);
相关问题