https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90203

            Bug ID: 90203
           Summary: Can't compare "const std::pair<int, int>" with
                    "std::pair<const int, int>"
           Product: gcc
           Version: 8.3.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: shreyans.doshi94 at gmail dot com
  Target Milestone: ---

Created attachment 46221
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=46221&action=edit
Complete error message

The following code works fine:

#include <algorithm>
#include <map>
#include <iostream>

using namespace std;

int main()
{
    map<int, int> a = {{1, 2}, {3, 4}};
    pair<const int, int> x = {1, 2};
    cout << count(a.begin(), a.end(), x);  // Outputs 1
    return 0;
}

But when I do the same thing inside count function using make_pair, it doesn't
work:

#include <algorithm>
#include <map>
#include <iostream>

using namespace std;

int main()
{
    map<int, int> a = {{1, 2}, {3, 4}};
    cout << count(a.begin(), a.end(), make_pair<const int, int>(1, 2)); //
Compilation error
    return 0;
}

Exact error message:
/usr/include/c++/7/bits/predefined_ops.h:241:17: error: no match for
‘operator==’ (operand types are ‘std::pair<const int, int>’ and ‘const
std::pair<int, int>’)
  { return *__it == _M_value; }
           ~~~~~~^~~~~~~~~~~

I've attached complete error message in a file with Description "Complete error
message" for reference. But I believe the issues is easy to reproduce on local
machine as well

Surprisingly, const pair<int, int> and pair<const int, int> are not comparable,
which it should be in such cases. Ideally, if a container is const, it should
imply that all the underlying members are also const.

To play around a little bit, I also tried to keep the type of x in the first
snippet to be "pair<const int, const int>" and it starts giving similar error
that it can't compare "pair<const int, int>" with "pair<const int, const int>".
Although this should have worked, but logically thinking, the case above where
the whole pair is const should be more likely to work in my opinion.

Although the error message I've given is from gcc7, I've tried the same thing
on gcc8.3, clang8 and even MSVC19.20 to see if any other compiler has the same
issue and it turns out that all of them are giving me same error.

Compilation flag: -g3 -std=c++17 -O3
I've also tried adding "-Wall -Werror -Wpedantic" and it gives me same error.

I'll be happy to give any more info if required by anyone.

Reply via email to