I am trying to make a priority queue with a custom compare function, as a data member of a class. The code fails to compile if I put the queue inside a class, however it works fine if it is inside the main
function:
#include <queue>
#include <vector>
using namespace std;
bool cmp(int x, int y) { return (x > y); }
class A {
public:
private:
priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // Error at pq(cmp) : function "cmp" is not a type name
};
int main() {
priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // no error here
return 0;
}
I am using Microsoft VS2015 for the above code. It makes no difference whether I put the cmp
function inside the class. Could you explain why this happens and a possible solution for this?
Edit 1:
This line in main
priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // no error here
does produce an error, but my IDE is not able to detect it. Use decltype(&cmp)
will eliminate this error.
First I was thinking about a bug in your compiler, but I could reproduce it. Then it suddenly became obvious:
foo bar(baz);
If you look closely, this is the same pattern as in your code. Due to the most vexing parse, this is a function declaration!
Thus you're trying to declare a function named pq
here, returning a priority queue and having a single parameter of type cmp
. The compiler isn't able to find that type, though.
Changing to use braced initialisation should fix this:
#include <queue>
#include <vector>
using namespace std;
bool cmp(int x, int y) { return (x > y); }
class A {
public:
private:
priority_queue<int, vector<int>, decltype(&cmp) > pq{cmp};
};
int main() {
// priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // this is wrong, too
return 0;
}
(Ideone)
Please don't ask me why it's working inside the function, though. It's not working inside the function, either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With