why is there ambiguity here cpp g++?

Viewed 62

I noticed that g++ faces ambiguity here.

int main()
{
    struct compare
    {
        vector<int> &v;
        const int n;
        compare(vector<int> &v) : v(v), n(v.size()) {}
        bool operator()(const vector<int> &a, const vector<int> &b)
        {
            for (int i = 0; i < n; i++)
                if (abs(a[0] - v[0]) != abs(b[0] - v[0]))
                    return abs(a[0] - v[0]) < abs(b[0] - v[0]);
            return false;
        }
    };

    vector<int> nums{1, 2, 3, 4};
    priority_queue<vector<int>, vector<vector<int>>, compare> pq1(compare(nums));
    priority_queue<vector<int>, vector<vector<int>>, compare> pq2((compare(nums)));
    struct compare2
    {
        const int v;
        compare2(const int &v) : v(v) {}
        bool operator()(const int &a, const int &b)
        {
            return abs(a - v) < abs(b - v);
        }
    };
    priority_queue<int, vector<int>, compare2> pq3(compare2(4));
    priority_queue<int, vector<int>, compare2> pq4((compare2(4)));
}

the compiler generates a warning:

/home/mahek/leetcode/prac/Solution.cpp:178:66: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
  178 |     priority_queue<vector<int>, vector<vector<int>>, compare> pq1(compare(nums));
      |                                                                  ^~~~~~~~~~~~~~~
/home/mahek/leetcode/prac/Solution.cpp:178:66: note: replace parentheses with braces to declare a variable
  178 |     priority_queue<vector<int>, vector<vector<int>>, compare> pq1(compare(nums));
      |                                                                  ^~~~~~~~~~~~~~~
      |                                                                  -
      |                                                                  {             -
      |                                                                                }

from which I understand pq1 is being considered a function. but I cannot understand what is the ambiguity here. compare(nums) cannot be a data type. Moreover, pq3 declaration doesn't generate any warning. also, the g++ suggests to use braces to declare pq1 as a variable. as in:

priority_queue<vector<int>, vector<vector<int>>, compare> pq1{compare(nums)}

ans it works fine. but i wish to know what is the ambiguity about.

0 Answers
Related