Is there any reason to not overload operator== as member, when only comparing to other object of the class?

前端 未结 2 395
花落未央
花落未央 2021-01-18 21:39

I\'ve been combing through the internet to find an answer, but I couldn\'t find any. The only reasons given seems to be relevant for comparing with objects of different type

2条回答
  •  佛祖请我去吃肉
    2021-01-18 22:30

    The arguments for using non-member operator overload for symmetric operations are based on style and consistency. They are not very strong arguments 1. Non-member overloads are typically preferred because a weak argument is still a little bit better than no argument at all.

    Your arguments for member operator overload don't seem to be any stronger. Consider following:

    No need to befriend the function

    On the other hand, if you use a non-member overload, then you don't have need to declare a member function. Is befriending the non-member somehow worse?

    or to provide getters for members

    There is no need for that if you befriend the overload.

    It is always available to class users (although this might be the downside also)

    It is unclear how this differs from the non-member overloads. Are they also not always available to the class users?

    No problems with lookup (which seems to be common in our GoogleTests for some reason)

    Are there lookup problems with non-member overloads? Could you demonstrate the problem with an example, and show how the problem is solved by using a member overload instead?

    If it does solve the problem, then you can of course use that. Just because some guidelines recommend that you prefer one alternative as a rule of thumb, doesn't mean that is the only alternative to be used in all use cases.


    1 Although, see answer https://stackoverflow.com/a/57927564/2079303 which is arguably stronger than just stylistic.

提交回复
热议问题