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.
.find
is wrapped in a function that returns a pair of optionals?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.find()
to make sure the returnediterator
is valid, in which case thestring
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 thestring
directly from the iterator, eg:if (it == numberToStr.end()){ return 1; } std::cout << it->second;