Davidius Davidius - 2 months ago 10
C++ Question

How to delete operator== (and !=) for floating point variables

Because of the unstability of floating points getting compared, I want to have at least a warning when using the comparison operator.


float a,b;
a == b; // Here the warning shall be thrown

How can I realize that?

I thought of overloading like:

inline bool operator==(const float& a, const float& b)
#warning "Usage of equal on floating point variables not allowed."
return false;

I didn't found it clear stated, but it seems that overriding of this operator is forbidden as MSVC throws C2803 and gcc throws "must have an argument of class or enumerated type" (also described in Global overloading of == and != for floating-points). Even if it would be possible, the compiler would throw an error when he comes across the #error statement even if not used.


Your approach with custom operator overload wont work because C++ standard forbids custom operator overloads if all their arguments have builtin types.

If you're using GCC (or clang/MinGW) you can use -Wfloat-equal to enable the warning about those comparsions. It's the closest thing you can get.

Even if it would be possible to completely disable them, it would be a bad idea. Sometimes they are useful and completely safe. Especially if there are no computations.

Consider following code:

float f = 0;

if (a >= -1 && a <= 1)
    f = std::asin(a);

// ...

if (f != 0)
    std::cout << "asin = " << f << '\n';
    std::cout << "Out of range.\n";

It's completely safe even though it uses == with float.