0

I wanted to test this very interesting answer and came out with this minimal implementation:

class A
{
    enum M { a };
    std::tuple<int> members;

public:

    A() { std::get<M::a>(members) = 0; }
    A(int value) { std::get<M::a>(members) = value; }
    A(const A & other) { members = other.members; }

    int get() const { return std::get<M::a>(members); }

    bool operator==(A & other) { return members == other.members; }
};

and a simple test:

int main() {

    A x(42);
    A y(x);

    std::cout << (x==y) << std::endl;

    return 0;
}

Everything's fine, until I define a simple struct B {}; and try to add an instance of it as a member. As soon as I write

std::tuple<int, B> members;

the operator== isn't ok anymore and I get this message from the compiler (gcc 5.4.1):

error: no match for ‘operator==’ (operand types are ‘std::__tuple_element_t<1ul, std::tuple<int, B> > {aka const B}’ and ‘std::__tuple_element_t<1ul, std::tuple<int, B> > {aka const B}’)
  return bool(std::get<__i>(__t) == std::get<__i>(__u))
                                 ^

I tried providing an operator== to B:

struct B
{
    bool operator==(const B &){ return true; }
};

and had an extra from compiler:

candidate: bool B::operator==(const B&) <near match>
     bool operator==(const B &){ return true; }
          ^

Can anyone explain what's wrong with B struct? Is it lacking something, or else?

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • 1
    Can you be more specific about "without luck"? Since the error message complains about not finding a `operator==(const B&, const B&)` adding it seems obvious. The question probably should be why it isn't found, but you need to change your question code for that. – nwp Mar 06 '18 at 11:37

1 Answers1

5

It's ultimately const correctness. You didn't const qualify B's (or A's, for that matter) comparison operator and its parameter consistently.

Since tuple's operator== accepts by a const reference, it cannot use your const-incorrect implementation. And overload resolution fails as a consequence.

Tidying up all of those const qualifiers resolves all the errors.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458