Global overloading of == and != for floating-points

一世执手 提交于 2019-12-12 14:21:58

问题


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 ?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/16795959/global-overloading-of-and-for-floating-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!