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

后端 未结 3 2115
梦谈多话
梦谈多话 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

    The rules for matching a member function against an argument are different from the rules for matching the first argument of a free function. I'm not certain exactly how they are different, but since they are different it's actually preferable to implement most binary operators as free functions instead of member functions in order that argument matching operates symmetrically for both arguments.

    There is an except for postfix ++, but that's because it isn't really a binary operator, and only plays one when you overload it in order to have a way of distinguishing between it and prefix ++.

提交回复
热议问题