Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ priority queue with custom compare function in a class

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.

like image 392
Fontaine007 Avatar asked Feb 21 '16 15:02

Fontaine007


1 Answers

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.

like image 123
Daniel Jour Avatar answered Oct 17 '22 01:10

Daniel Jour