0

When having a look at the documentation of std::map, I noticed that the lexicographical comparison operators (between maps) were not counted as member functions. Checked a few other containers (vector, list, etc.) and saw the same situation for them also. Is there a reason for that? Aren't those operators overloaded inside those container classes?

Here is a related answer arguing the basic rules of operator overloading.

Caglayan DOKME
  • 948
  • 8
  • 21
  • 1
    Most operators can be overloaded either as member or as non-member functions. I'd say the latter are better, because they treat both arguments the same way (e.g. member ones don't allow implicit conversions for the lhs). – HolyBlackCat Nov 20 '21 at 15:12
  • 1
    @KamilCuk It's not just about `std::map`. Even the `std::basic_string` implements those operators as non-member functions. I'm looking for the reason for that design choice. – Caglayan DOKME Nov 20 '21 at 15:21
  • @HolyBlackCat Thanks for the answer. Where would we need an implicit conversion for the `lhs` parameter? Is there another reason for the latter? – Caglayan DOKME Nov 20 '21 at 15:24
  • 1
    The example with the conversion: https://stackoverflow.com/a/52938077/2752075 Though I wasn't able to do the same thing with standard containers. *"Is there another reason"* I don't know any. – HolyBlackCat Nov 20 '21 at 15:33
  • @JaMiT I meant that the documentation classifies the methods according to their relations and operations. The lexicographical comparison operators are in a group called *non-member* functions. – Caglayan DOKME Nov 20 '21 at 17:36
  • Oh, you mean specifically what would be `std::map::operator<` and its friends. I had read that as the comparison operator of the keys. – JaMiT Nov 20 '21 at 17:44
  • 2
    Do you want *a* reason, or *the* reason? I don't know what the standards committee was thinking, but SO's go-to answer on the subject, [A: What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/a/4421729), does give the advice *"If a binary operator treats both operands equally (it leaves them unchanged), implement this operator as a non-member function"*, which applies here. – JaMiT Nov 20 '21 at 17:49
  • @JaMiT From what you've shared, I see that there isn't a single reason. Some best practices and limitations drive the designer to implement some of the operators as non-member functions. Now it is more clear for me, thanks for your time. – Caglayan DOKME Nov 21 '21 at 08:05

0 Answers0