Is there a reason for missing transparent (template <class K> at(K&& key);) in std::map?
Asked
Active
Viewed 483 times
9
-
1It does not have transparent `operator[]` either – Slava Nov 23 '16 at 14:38
-
@Slava, but it does have a transparent `find`. – StoryTeller - Unslander Monica Nov 23 '16 at 14:39
-
1I would not want it. Key is a specific type, and I do not want a templated function which would take anything, only to give me sheets of errors whenever I mistype the argument. – SergeyA Nov 23 '16 at 14:51
-
@StoryTeller, this is very different. `find` is expected to be transparent, simply because the same find expressed as explicit loop would be transparent. – SergeyA Nov 23 '16 at 14:51
-
2@SergeyA It wasn't expected to be transparent until c++14. We implicitly converted to `Key` for both operations. It's a valid question and contrast. – StoryTeller - Unslander Monica Nov 23 '16 at 14:57
1 Answers
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
-
4this is indeed correct! I would leave my comment there for future readers, but it's logically retracted. – SergeyA Nov 23 '16 at 15:26
-
2Also, 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
-
@T.C. and `at` is an established non-option for multimaps. Okay, makes sense now, thanks :) – krzaq Nov 24 '16 at 11:34