C++: How to avoid unwanted comparison because implicit convert to bool

Viewed 70

I have a class like this:

#include <stdio.h>


class A {
    public:
        operator bool() const { return m_value != 0; }
        int m_value {0};
};


int main() {
        A a = A();
        a.m_value = 1;
        A b = A();
        b.m_value = 2;
        if (a == b) {
                printf("Wrong!\n");
        }
}

I forget to override the comparison operator for A. But because the operator bool, this code compiles without even a warning, result in an unwanted comparison.

Is there a way I can detect behavior like this automatically? like a compile flag.

1 Answers

This is exactly what the explicit specifier is for:

   explicit operator bool() const { return m_value != 0; }
// ^^^^^^^^

Now implicit conversions from A to bool will be a hard compiler error.

Here's a demo.

Related