const std::map operator []

367 views
Skip to first unread message

Cleiton Santoia

unread,
Nov 4, 2017, 7:18:59 PM11/4/17
to ISO C++ Standard - Future Proposals
What about include a 'const operator []' in std::map that returns a std::optional instead a reference to T ?

std::optional< std::reference_wrapper< T > > operator[] (const Key& key) const { ... }

Maybe this is a case for committee consider std::optional for references

std::optional< T& > operator[] (const Key& key) const { ... } 

BR
Cleiton




Nicol Bolas

unread,
Nov 4, 2017, 8:36:10 PM11/4/17
to ISO C++ Standard - Future Proposals


On Saturday, November 4, 2017 at 7:18:59 PM UTC-4, Cleiton Santoia wrote:
What about include a 'const operator []' in std::map that returns a std::optional instead a reference to T ?

std::optional< std::reference_wrapper< T > > operator[] (const Key& key) const { ... }


First, it would have to be a `const T`.

Second, ignoring the question of `optional<reference_wrapper<const T>>` vs. `const T*`, to have the `const` and non-`const` overloads of a function return such disparate types is not reasonable. They're supposed to be functions that do the same thing.

Yes, it's unfortunate that `operator[]` potentially modifies the object. It would perhaps have been better if it were more like `find` or something. But that ship has sailed. Creating an interface that behaves in such a different way from the other overload is not a good solution to this problem.


Message has been deleted

Zach Laine

unread,
Feb 20, 2018, 11:17:32 AM2/20/18
to std-pr...@isocpp.org
On Tue, Feb 20, 2018 at 7:17 AM, <frederik...@gmail.com> wrote:
I've considered doing similar things a few times. I usually opt for throwing an exception if the key doesn't match an item however.

That's not a very exceptional circumstance, nor is it an error.  An optional is a much better convention is such code.

Zach


olafv...@gmail.com

unread,
Feb 26, 2018, 6:04:12 AM2/26/18
to ISO C++ Standard - Future Proposals
Op zondag 5 november 2017 00:18:59 UTC+1 schreef Cleiton Santoia:
A wrapper returning second_type* is so much easier. See my find_ptr and friends.

const typename T::value_type::second_type* find_ptr(const T& c, const U& v)

Reply all
Reply to author
Forward
0 new messages