C ++ priority queue with custom compare function in class

I am trying to do a priority queue with a custom comparison function, as a class data item. The code does not compile if I put the queue inside the class, however it works fine if it is inside the function main:

#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 doesn't matter if I put the element cmpinside the class. Could you explain why this is happening and a possible solution for this?

Change 1:

This line in main

priority_queue<int, vector<int>, decltype(cmp) > pq(cmp); // no error here

causes an error, but my IDE cannot detect it. Use decltype(&cmp)will fix this error.

+4
source share
1 answer

, . :

foo bar(baz);

, , . - !

, pq , cmp. .

:

#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)

, , . .

+7

Source: https://habr.com/ru/post/1629786/


All Articles