Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion of both operands for operator==

Tags:

c++

The following code compiles and executed without error even though no equality operator is defined:

class A {
public:
    operator bool() const { return true; }
};


int main()
{
    A a, b;
    a == b; //why does this compile?
    return 0;
}

What happens internally for a == b is that the operator bool() const is called for both operands, and then the two booleans are compared for equality (this happened in our production code where class A was a smart pointer type, and gave semantically dubious results).

My question is: What rule in the C++ standard allows for the implicit conversion of both operands in this case? I can understand that one operand would be implicitly converted to bool for the test for equality if the other operand was already a bool, but not both.

like image 520
Dreamer Avatar asked Jan 24 '17 10:01

Dreamer


1 Answers

I can understand that one operand would be implicitly converted ..., but not both

Then you've misunderstood. EDIT: According to the experts in comments, argument dependent lookup appears to be a case where your assumption is correct. But yours isn't a case of ADL.

What rule in the C++ standard allows for the implicit conversion of both operands

From standard draft:

[over.match] (2.9)

  • Then the best viable function is selected based on the implicit conversion sequences (13.3.3.1) needed to match each argument to the corresponding parameter of each viable function.

My emphasis on "each argument". Not "a single argument".

like image 192
eerorika Avatar answered Nov 03 '22 14:11

eerorika