How to avoid nested if statements with chained optionals in C++?
For example, if type A contains an std::optional<B> b
and type B an std::optional<C> c
, I would like to be able to write something like:
const auto v = if_exists(if_exists(a->b)->c);
And v would get the value from c or an empty optional if either b or c are empty optionals.
I think this would be nicer that nested ifs like this:
if (a->b) {
const auto b = *(a->b);
if (b->c) {
const auto c = *(b->c);
}
}
The following question seems to go in this direction but I am not sure how to adapt it to my use-case: Haskell style "Maybe" type & *chaining* in C++11
This can be achieved with a simple macro.
#define CHAIN(OPTIONAL, MEMBER) \
([](auto &&opt) { \
return opt ? std::optional{opt->MEMBER} : std::nullopt; \
}(OPTIONAL))
const auto v = CHAIN(CHAIN(a, b), c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With