Question

Is it a bad practice to overload global operator == and != for floating points ? I'm using fast floating-points in a game environement, and i was thinking about using fuzzy comparison everywhere as i can't imagine a situation where i don't expect extremely close numbers not to be equals.

Any advice ?

Was it helpful?

Solution 2

Other posts mentioned technical problems, from another perspective:

Its a bad practice because nobody expects these operators to be overloaded, while reasonable people will expect an almostEquals function. Its strange and odd and masks what is really going on.

OTHER TIPS

You can't. C++ operator overloads must involve at least one user-defined type.

And even if you could, it would probably be a bad idea. Users expect equality to be transitive, i.e. if a == b and b == c, then a == c. It sounds like your fuzzy comparison would not be transitive.

The problem is: if you could actually do that, and in the code you saw something like:

if ( a == b ) {
    // more things...
}

Would you know if it is invoking the regular comparison or the, say, fuzzyCompare() function? In order to distinguish between both, you would have to look up in the code what is the type of a and b... You wouldn't be able to read your own code without asking yourself a lot of questions, and probably cross-referencing a lot of variables with their types.

This is exactly the scenario in which operator overloading becomes a nightmare, and the reason its abuse led it to be dropped for languages such as Java.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top