Boost logo

Boost :

From: Ivan Matek (libbooze_at_[hidden])
Date: 2024-12-21 15:26:12


On Sat, Dec 21, 2024 at 1:11 PM Peter Dimov via Boost <boost_at_[hidden]>
wrote:

>
> if( auto p = lookup( map, key ) )
> {
> // do something with *p
> }
>

Ignoring pointer vs optional<T&> discussion I think this is best you can do
now(although stylistically I would here always write auto* p ).

>
> If there's a built-in way to obtain an optional<mapped_type&> 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::vector<std::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::to<std::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 to<std::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
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk