What’s the reason for the following behavior?
class BoolWrapper
{
public:
BoolWrapper(bool value) : value(value) {}
operator bool() const { return value; }
operator int() const { return (int) value; }
private:
bool value;
};
BoolWrapper bw(true);
if (bw) { ... } // invokes operator bool()
if (bw == true) { ... } // invokes operator int() -- why?
Is this behavior expected? (Using GCC 4.7.2.)
Your expectations are based on your belief that the language already knows how to compare two
boolvalues. In reality it doesn’t, however surprising it might sound. More precisely, the language “does not know” how to do it directly.At the conceptual level, C++ does not have a dedicated built-in equality comparison operator for
bool vs. boolcomparisons. Even when you writetrue == falsein your code, it is really interpreted by the language as(int) true == (int) false. The implicit conversion tointis introduced by the rules of usual arithmetic conversions andint vs. intcomparison is used afterwards.The most immediate built-in operator that can compare two
boolvalues is the one forint vs. intcomparison. This is the operator the compiler is trying to use in your case as well. The very same operator will be used forchar vs. charandshort vs. shortcomparisons.In other words, the only way the compiler can use your
boolconversion operator in thebw == trueexpression would be to doThis is certainly less “optimal” than the direct
This is the logic that drives the language to select the latter variant.