Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot instantiate a binary_function for std::less / std::greater

I'm trying to write a function that will print the contents of both minheap and maxheap but I'm having trouble with the comparators. I tried using a ternary operator, but it doesn't work since std::less and std::greater are different types. What is wrong with how I am trying to use the comparators?

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

Link error:

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


edit:

I've also tried using a binary_function pointer and allocating on the heap, and now i get a different error:

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

error:

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

like image 668
xst Avatar asked Jul 27 '26 00:07

xst


1 Answers

You are the victim of object slicing.

When you assign less<T> or greater<T> to the binary_function type, the operator() they define is gone.

From my favorite reference:

binary_function does not define operator(); it is expected that derived classes will define this. binary_function provides only three types - first_argument_type, second_argument_type and result_type - defined by the template parameters.

You should pass less<T> or greater<T> in directly. You can also use pointer_to_binary_function, but they've both been deprecated in C++11 in favor of function.

like image 102
Collin Avatar answered Jul 29 '26 14:07

Collin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!