ldytmac
ldytmac

Reputation: 83

Conflict when trying to initialize a priority queue using another comparison functor other than the one declared in the template signature

I implemented a templated priority queue:

template<typename TYPE, typename COMP_FUNCTOR = std::less<TYPE>>
class heap_priority_queue : public priority_queue<TYPE, COMP_FUNCTOR> {
public:
    typedef unsigned size_type;

    template<typename InputIterator>
    heap_priority_queue(InputIterator start, InputIterator end, COMP_FUNCTOR comp = COMP_FUNCTOR()); 
    /* other methods*/
};

template<typename TYPE, typename COMP_FUNCTOR>
template<typename InputIterator>
heap_priority_queue<TYPE, COMP_FUNCTOR>::heap_priority_queue (
    InputIterator start, InputIterator end, COMP_FUNCTOR comp) {

    for(auto it = start; it != end; ++it) {
        data.push_back(*it);
    }
    fix();
    this->compare = comp;
} 

The default comparison functor defined in the template signature is std::less, but in the constructor of this priority_queue, it seems we can pass another custom COMP_FUNCTOR comp as the 3rd arguments, or we are using the COMP_FUNCTOR declared in the template signature? But when I tried to pass another COMP_FUNCTOR other than the one declared in the template signature as the third argument conflict happens,why? Here is the code:

class isgreater {
public:
    isgreater() {};
    bool operator () (int a, int b) {
        return a > b;
    }
};
int main() {
    int my_ints[] = {1, 3, 5, 7, 9};
    vector<int> v(my_ints, my_ints + sizeof(my_ints)/sizeof(int));

    // wrong, default COMP_FUNCOR is std::less, which is different from isgreater;
    heap_priority_queue<int> sq(v.begin(), v.end(), isgreater());

    // right, no conflict
    heap_priority_queue<int, isgreater> back_up(v.begin(), v.end(), isgreater());

Why should the object we pass in as the third argument of the constructor be the same as the one we declare in the template signature? It seems to me make no sense to keep the third argument of the constructor since we must use the one defined in the template signature...Thank you.

Upvotes: 0

Views: 115

Answers (1)

stryku
stryku

Reputation: 750

// wrong, default COMP_FUNCOR is std::less, which is different from isgreater;
heap_priority_queue<int> sq(v.begin(), v.end(), isgreater());

is equal to

heap_priority_queue<int, std::less<int>> sq(v.begin(), v.end(), isgreater());

and compilator don't know how convert from isgreater to std::less<>

Upvotes: 1

Related Questions