3

Consider following code:

#include<functional>
#include<iostream>
#include<map>

const std::map<int, std::string> numberToStr{{1, "one"}, {2,"two"}};
int main() {
    auto it = numberToStr.find(2);
    if (it ==numberToStr.end()){
        return 1;
    }
    const auto&[_, str] = *it;
    std::cout << str;
}

Is there any way for me to do the unwrapping of potentially dereferenced it to 2 optionals(_ and str) so I can then write:

const auto&[_, str] = // some magic;
// _ is std::optional<int>, str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;
}

I presume not since structured bindings are language level thing, and std::optional is a library feature and afaik there is no way to customize the interaction.

Note: I presume I could implement my own map that returns iterators that know if they point to .end(), and "hack" customization points to do optional logic based on that, I am asking for general use case when I do not control the container.

7
  • 2
    I don't follow. If you don't control the container, you get what you get. What sort of magic are you expecting? Is it fine if the call to .find is wrapped in a function that returns a pair of optionals?
    – cigien
    Dec 3, 2020 at 16:33
  • @cigien I hit a wall, if I knew a some direction to solution I would provide it, but I only know what I want(unpacking maybe pair that .find returns into pair of optional-s), Nathan answer is I think best I can get without WG21 baking stuff like this into language... Dec 3, 2020 at 16:57
  • Sure, that's fine. Your wording threw me off a bit that's all. BTW this would not be a language issue anyway, but a library issue, since it deals with what map::find returns. So it would be up to LWG, I think. Not that the signature is ever going to be changed to do what you want.
    – cigien
    Dec 3, 2020 at 17:04
  • This question doesn't make sense to me. The code is already checking the result of find() to make sure the returned iterator is valid, in which case the string for that map element is also valid and can't be optional. There is no need to use a structured binding at all when you can just access the string directly from the iterator, eg: if (it == numberToStr.end()){ return 1; } std::cout << it->second; Dec 3, 2020 at 20:16
  • 1
    @cigien: No problem: there’s a website to tell you these things, but you have to know it exists! Dec 3, 2020 at 22:02

3 Answers 3

6

You could add a helper function like

template <typename Key, typename Value, typename... Rest>
std::pair<std::optional<Key>, std::optional<Value>> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find)
{
    auto it = map.find(to_find);
    if (it == map.end())
        return {};
    else
        return {it->first, it->second};
}

and then you would use it like

const auto&[_, str] = my_find(numberToStr, 2);
// _ is std::optional<int>, str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;

If you only care about the value, you can shorten the code a bit by just returning it instead with

template <typename Key, typename Value, typename... Rest>
std::optional<Value> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find)
{
    auto it = map.find(to_find);
    if (it == map.end())
        return {};
    else
        return {it->second};
}

and then you'd use it like

auto str = my_find(numberToStr, 2);
// str is std::optional<str>
if (!str){
    return 1;
}
std::cout << *str;
11
  • Yup, probably what the OP wants, nice answer :) I shouldn't have waited for confirmation on the comment :(
    – cigien
    Dec 3, 2020 at 16:40
  • 1
    This is what OP asked for, but I think they'd be better served by std::optional<Value> my_at(const std::map<Key, Value, Rest...>& map, const Key& to_find)
    – Caleth
    Dec 3, 2020 at 16:42
  • @Caleth good point. added that into the answer. Dec 3, 2020 at 16:45
  • What's the point of wrapping find like this anyway? Dec 3, 2020 at 16:48
  • 1
    @NoSenseEtAl optional<reference_wrapper<T>> is a lengthy way of spelling T*
    – Caleth
    Dec 3, 2020 at 17:52
5

The more C++20-idiomatic route would be to model the iterator as a possibly-empty range:

auto const rng = std::apply(
    [](auto it, auto end) { return std::ranges::subrange(it, end); },
    numberToStr.equal_range(2));
if (rng.empty())
    return 1;
auto const& [_, str] = *rng.begin();
std::cout << str;

Example.

You can do this before C++20 using Boost.Ranges, which has a rather more ergonomic iterator_range:

auto const rng = boost::make_iterator_range(numberToStr.equal_range(2));
// ditto
3
  • Could you please explain why checking an empty range is better/more idiomatic than checking whether an iterator points to the end? Isn't that kinda what an empty range would be?
    – Cedric
    Dec 3, 2020 at 16:49
  • 1
    @Cedric it allows writing clearly-correct code using a for loop to guard access into the (possibly-empty) range. See open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1255r6.html
    – ecatmur
    Dec 3, 2020 at 16:57
  • @Cedric to me range stuff is less idiomatic, but maybe it is just a thing of getting used to it, I remember I disliked boost::optional when I saw it for the first time... Dec 3, 2020 at 17:38
4

The desired API makes little sense to me. Why would you get back two optionals? The key is either in the map or not, that's a single dimension of optionality - it's not like you can get back an engaged key but a disengaged value or a disengaged key but an engaged value.

The API should be:

template <typename Map, typename Key>
auto try_find(Map&, Key&&) -> optional<range_reference_t<Map>>;

But we can't actually write that using std::optional, because that one doesn't support optional references. Returning an actual optional<value_type> is both wasteful (extra copies) and likely semantically invalid (you probably wanted that specific value, not just a value).

So the first step is acquiring a better implementation of optional and using that. At which point, the implementation here is very easy:

template <typename Map, typename Key>
auto try_find(Map& m, Key&& k) -> optional<range_reference_t<Map>>
{
    auto it = m.find(std::forward<Key>(k));
    if (it != m.end()) {
        return *it;
    } else {
        return nullopt;
    }
}

A different approach, which does work with std::optional, is to return an optional iterator instead of an optional reference. This has the benefit of being just as composable as optional while still working entirely within the standard library.


A third approach is to instead return a range:

template <typename Map, typename Key>
auto try_find(Map& m, Key const& k) -> subrange<iterator_t<Map>>
{
    auto [f, l] = m.equal_range(key);
    return subrange(f, l);
}

This continues to be composable with all the ranges things. You just check for emptiness instead of engaged-ness:

auto r = try_find(m, key);
if (r.empty()) {
    // nope
} else {
    // use r.front()
}
4
  • Well it is personal preference, I prefer that I can check just str and use it immediately, without need to first check the pair is fine, and then get .second from it. I had a long discussion on other A comments, this is my personal preference, hard to force somebody to agree. :) Same with optional of iterator, I do not like ** (or equivalent) syntax. Still upvoted the answer since I had no idea aboutoptional<range_reference_t<Map>> Dec 3, 2020 at 17:33
  • 1
    std::optional<std::reference_wrapper<ValueType>> is also an option (sic).
    – ecatmur
    Dec 3, 2020 at 17:57
  • @ecatmur But that's not what you want to do, it's just a hack around a library deficiency. range_reference_t<M> need not have been an actual reference type, maybe I have a map that yields proxies - I'd want to preserve that. The other issue is it's not optional<reference_wrapper<range_value_t<M>> - it's more like optional<reference_wrapper<remove_reference_t<range_reference_t<M>>>>. But then that is valid even if we have proxies, and we're returning dangling references unconditionally. It's kind of a mess.
    – Barry
    Dec 3, 2020 at 18:22
  • Well, that's optional<conditional_t<is_reference_v<range_reference_t<M>>, reference_wrapper<remove_reference_t<range_reference_t<M>>>, range_reference_t<M>>> then. It's a shame that we have unwrap_reference but not the reverse operation.
    – ecatmur
    Dec 3, 2020 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.