jeudi 25 février 2016

Unable to pass derived Compare to std::priority_queue

I need to pass a derived comparator to std::priority_queue, but for some reason the base class' operator() is being called.

Here is a minimal code that shows this behavior:

class Base {
    public:
    virtual bool operator() (int l, int r) const {
        cout << "Should not be called" << std::endl;
        return 0;
    }
    virtual ~Base() {}
};
class A : public Base { 
    public:
    bool operator() (int l, int r) const override {
        cout << "Should be called!!!!";
        return l < r;
    }
};
int main() {
    priority_queue<int, vector<int>, Base> pq((A()));
    pq.push(1);
    pq.push(2);
    pq.push(3);
    pq.push(0);
    cout << pq.top();
    return 0;
}

The code is available on ideone as well

Note that I cannot use priority_queue<int, vector<int>, A>, because I have other subclasses for Base, and that will result in a lot of code duplication1.

What am I doing wrong?


(1) I know I can bypass the code duplication issue by using template functions that accept priority_queue<int,vector<int>, T> - but I really rather not to.

Aucun commentaire:

Enregistrer un commentaire