Why should I overload a C++ operator as a global function (STL does) and what are the caveats?

后端 未结 3 2099
梦谈多话
梦谈多话 2020-12-07 02:45

Why would I want to overload a C++ operator() as global and not member function. For example, the == operator.

Why is this done? for example in STL libr

3条回答
  •  执笔经年
    2020-12-07 03:16

    If I remember correctly, operator = must be a member function. Regarding operator ==, I figure you don't actually mean global but free function instead (STL does not define operators globally). There are a couple of things to consider, one is decoupling from the class itself: If your operator can be defined in terms of the public interface of your class, then you are better off implementing it that way to keep the access to the implementation internals to the bare minimum. The other fundamental advantage is the possibility to implemement an operator where your type comes as the second operand, consider equality between types T and U:

    bool operator ==( T const& t, U const& u ){ ... }
    bool operator ==( U const& t, T const& u ){ ... }
    

    If objects of type T and U can be equally compared, then it makes sense that both t == u and u == t are valid and both yield the same result. If you were defining this operator as a member function, then one would be within the implementation of T and the other within the implementation of U. Now consider U is a 3rd party type outside your control, or even better is a fundamental type such as int, now there is no other way for you to provide such operator but to provide the free function version of it.

提交回复
热议问题