0

i have code like this

priority_queue<int, std::vector<int>, decltype(&VD::CompareByDistance)> pqDistances(&VD::CompareByDistance);

where

class VD 
{
    ...
    bool CompareByDistance(int indexLeft, int indexRight) const;
};

But i get error

error C2064: term does not evaluate to a function taking 2 arguments

How can i pass class member as a compator, the thing is that i want comparator to access its instance fields. Thanks.

2
  • Btw, is this comparison function really non-const? That does not feel very idiomatic. Commented Jun 15, 2015 at 13:34
  • @BaummitAugen it is const, thanks Commented Jun 15, 2015 at 13:36

1 Answer 1

1
bool CompareByDistance(int indexLeft, int indexRight);

takes three arguments: The this-pointer and the both ints.

Besides this being the wrong number of arguments for the priority_queue template parameter: What instance of VD do you expect this non-static method to be called on?

A workaround for this would be "carrying" the instance with you like this:

VD v;
auto comp = [&](int i1, int i2) {return v.CompareByDistance(i1, i2);}

This comp object would now be a valid template argument for your queue. For example:

struct A{
    bool compare (int, int) const {return true;}
};

int main()
{
    A a;
    auto comp = [&](int i, int i2) {return a.compare(i, i2);};
    std::priority_queue<int, std::vector<int>, decltype(comp)> q (comp);
}
Sign up to request clarification or add additional context in comments.

6 Comments

i have the same error. The lambda captures this, and it is a problem
@Yola Did you forget to pass the comp to the constructor of the queue? Works for me. (Live)
Is the 'this' pointer actually used in CompareByDistance though? Otherwise we could simply make it static
@KABoissonneault " the thing is that i want comparator to access its instance fields." So I guess that won't work.
@BaummitAugen Alright, missed that line. Unrelated, but I don't recommend using generalized lambda capture. The capture list should be [&v] or [&a] instead.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.