mercredi 21 février 2018

Chain Optionals in C++

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

Aucun commentaire:

Enregistrer un commentaire