
On Sat, Dec 21, 2024 at 1:11 PM Peter Dimov via Boost
if( auto p = lookup( map, key ) ) { // do something with *p }
Ignoring pointer vs optional
If there's a built-in way to obtain an optional
instead of an iterator, I can use that instead of `lookup`, without changing the syntax.
Yes, but it is also possible to skip if E.g. https://godbolt.org/z/5rM6q9fME std::vectorstd::string books_titles_for_user(const uint64_t user_id) { return user_id_to_books.try_at(user_id).map([](const auto& books){ return books | sv::transform(&Book::title) | sr::tostd::vector(); }).get_value_or({}); } I know some people hate "fancy" syntax like this, some love it, just saying that with pointer you do not have map(aka transform) chaining. If people dislike tostd::vector there is another way in godbolt link, but it is not prettiest code I ever saw :)
Although it strikes me that it should probably be named `try_at` instead of `try_find`. `find` is already a try-ing member function, because it doesn't fail, whereas `at` both returns the correct reference type, and can fail.
I agree https://lists.boost.org/Archives/boost//2024/12/258845.php
Of course `try_at` by convention ought to return boost::system::result or std::expected instead of an optional, but that's another story.
I disagree :) https://lists.boost.org/Archives/boost//2024/12/258802.php
Interestingly, and maybe relevant for this discussion, `at` was added to associative containers even though it could have been made a free function instead.
Never thought about this, but now that you bring it up, I presume same is true for std::vector/array/deque..., no? std::at would be something like //... // ...if constexpr we are RA iterator container if (idx < c.size()) { return c[idx]; } else { // throw }