【问题标题】:Cannot instantiate a binary_function for std::less / std::greater无法为 std::less / std::greater 实例化 binary_function
【发布时间】:2012-10-10 15:39:07
【问题描述】:

我正在尝试编写一个函数来打印 minheap 和 maxheap 的内容,但是比较器遇到了问题。我尝试使用三元运算符,但它不起作用,因为 std::less 和 std::greater 是不同的类型。我尝试使用比较器的方式有什么问题?

#include <functional>
template<typename T> void printheap (T* v, int begin, int end, bool max) {
    end--;

    std::binary_function<T,T,bool> comp;
    if (max) comp = less<T>();
    else comp = greater<T>();

    while (end>=begin) {
        cout << v[begin] << " ";
        pop_heap(&v[begin], &v[end+1], comp );
        end--;
    }
    cout << endl;
}

链接错误:

/usr/include/c++/4.6/bits/stl_heap.h:305:4: error: no match for call to ‘(std::binary_function&lt;int, int, bool&gt;) (int&amp;, int&amp;)’


编辑:

我也尝试过使用 binary_function 指针并在堆上分配,现在我得到了一个不同的错误:

template<typename T> inline void printheap (T* v, int begin, int end, bool max) {
    ...
    std::binary_function<T,T,bool> *comp;
    if (max) comp = new less<T>();
    else comp = new greater<T>();
    ...
        pop_heap(&v[begin], &v[end+1], (*comp) );
    ...
delete comp;
}

错误:

/usr/include/c++/4.6/bits/stl_heap.h:305:4: error: ‘__comp’ cannot be used as a function

【问题讨论】:

  • 也使用std::function 代替binary_function,因为后者在C++11 中已被弃用。这可能会解决您的问题。
  • 我确实忘记取消引用,但这样做又会产生第一个编译器错误

标签: c++ algorithm data-structures stl functional-programming


【解决方案1】:

你是object slicing的受害者。

当您将less&lt;T&gt;greater&lt;T&gt; 分配给binary_function 类型时,他们定义的operator() 就消失了。

来自my favorite reference

binary_function 没有定义 operator();预计派生类将定义这一点。 binary_function 仅提供三种类型 - first_argument_type、second_argument_type 和 result_type - 由模板参数定义。

您应该直接传入less&lt;T&gt;greater&lt;T&gt;。您也可以使用pointer_to_binary_function,但它们在 C++11 中都已被弃用,取而代之的是 function

【讨论】:

  • +1,但是取消引用指针会产生对 binary_function 的引用,它没有定义 operator(),所以他仍然会得到一个错误。他应该使用std::function
猜你喜欢
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多