9

Is there a reason for missing transparent (template <class K> at(K&& key);) in std::map?

Community
  • 1
  • 1
bobah
  • 17,620
  • 1
  • 35
  • 63

1 Answers1

7

My guess is that std::map::at() must be a "bounds-checked" version of std::map::operator[](). Providing a transparent version of std::map::operator[]() imposes an additional requirement on std::map::key_type and the query key type K - if the query key is not in the map, it must be inserted (with default constructed value), which means that std::map::key_type must be constructible from the the query key type.

Leon
  • 29,760
  • 4
  • 60
  • 86
  • Not sure if I buy this argument. If the type is convertible, it is the same as being constructible from it. – SergeyA Nov 23 '16 at 15:20
  • 4
    @SergeyA The two types are not required to be convertible - they are only required to be comparable through a transparent comparator. – Leon Nov 23 '16 at 15:22
  • 4
    this is indeed correct! I would leave my comment there for future readers, but it's logically retracted. – SergeyA Nov 23 '16 at 15:26
  • 2
    Also, unlike the homogeneous case, there's no requirement that a heterogeneous key compares equivalent to at most one key in the map. What do you return if more than one key is a match? – T.C. Nov 24 '16 at 09:25
  • 1
    @T.C. The same argument could be made for `find`, but there's a transparent `find`. – krzaq Nov 24 '16 at 11:31
  • 3
    @krzaq except that `find` is an established operation for multimaps too. – T.C. Nov 24 '16 at 11:33
  • @T.C. and `at` is an established non-option for multimaps. Okay, makes sense now, thanks :) – krzaq Nov 24 '16 at 11:34